Merge branch 'main' into flutter/p1-pipelines

This commit is contained in:
2026-10-21 19:09:32 +01:00
304 changed files with 40777 additions and 159 deletions
+52
View File
@@ -0,0 +1,52 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/app_route.dart';
void main() {
test('parses each destination and a run detail', () {
expect(AppRoute.parse('/pipelines'), AppRoute.pipelines);
expect(AppRoute.parse('/runs'), AppRoute.runs);
expect(AppRoute.parse('/runs/12'), AppRoute.run(12));
expect(AppRoute.parse('/chat'), AppRoute.chat);
expect(AppRoute.parse('/settings'), AppRoute.settings);
});
test('normalises slashes and accepts a full URL, query and fragment', () {
expect(AppRoute.parse('/runs/'), AppRoute.runs);
expect(AppRoute.parse('/pipelines///'), AppRoute.pipelines);
expect(
AppRoute.parse('http://127.0.0.1:8096/runs/7?action=decide#top'),
AppRoute.run(7),
);
expect(AppRoute.parse('/runs/7/'), AppRoute.run(7));
});
test('a malformed or unknown location is the default Pipelines route', () {
for (final path in [
'',
'/',
'/runs/abc',
'/runs/0',
'/runs/-1',
'/runs/1/extra',
'/pipelines/2',
'/chat/session',
'/unknown',
'/runs/%E0%A4%A',
]) {
expect(AppRoute.parse(path), AppRoute.pipelines, reason: path);
}
});
test('serialises every route back to a parsable path', () {
for (final route in [
AppRoute.pipelines,
AppRoute.runs,
AppRoute.run(3),
AppRoute.chat,
AppRoute.settings,
]) {
expect(AppRoute.parse(route.path), route);
}
expect(AppRoute.run(3).path, '/runs/3');
});
}
+174
View File
@@ -0,0 +1,174 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/app_session.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
Future<void> flush() => Future<void>.delayed(Duration.zero);
Future<void> waitFor(bool Function() condition, String reason) async {
for (var attempt = 0; attempt < 200; attempt++) {
if (condition()) return;
await Future<void>.delayed(const Duration(milliseconds: 5));
}
fail('Timed out: $reason');
}
List<String> types(FakeChannel channel) => [
for (final frame in channel.outgoing)
(jsonDecode(frame as String) as Map<String, dynamic>)['type'] as String,
];
void main() {
test('Retry preserves an endpoint changed through shared Settings', () async {
final endpoints = <Uri>[];
final client = PipelinesClient(
channelFactory: (uri) {
endpoints.add(uri);
return FakeChannel()..readyCompleter.complete();
},
);
final session = AppSession(
endpoint: Uri.parse('ws://original.test/connect'),
client: client,
);
addTearDown(session.dispose);
await session.start();
final changed = Uri.parse('ws://selected.test/connect');
await session.client.connect(changed);
await session.stop();
await session.retry();
expect(endpoints, [
Uri.parse('ws://original.test/connect'),
changed,
changed,
]);
expect(session.endpoint, changed);
});
test(
'start subscribes once, stop unsubscribes, and the app owns the socket',
() async {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final session = AppSession(
endpoint: Uri.parse('ws://example.test/connect'),
client: client,
);
await session.start();
await flush();
expect(session.connected, isTrue);
expect(types(channel), ['subscribe']);
final frame = jsonDecode(channel.outgoing.single as String) as Map;
expect(frame['workspace'], '');
await session.stop();
await flush();
expect(types(channel), ['subscribe', 'unsubscribe']);
expect(session.connected, isFalse);
session.dispose();
},
);
test('reconnect subscribes the new socket again', () 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: 5),
);
final session = AppSession(
endpoint: Uri.parse('ws://example.test/connect'),
client: client,
);
addTearDown(session.dispose);
await session.start();
await flush();
expect(types(first), ['subscribe']);
expect(session.connectionEpoch, 1);
first.incoming.addError(StateError('network drop'));
await waitFor(
() => sockets == 2 && session.connected && second.outgoing.isNotEmpty,
'reconnected socket did not subscribe',
);
expect(types(second), ['subscribe']);
expect(session.connectionEpoch, 2);
});
test('a subscribe ack marks the watch live, a refusal reports it', () async {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final session = AppSession(
endpoint: Uri.parse('ws://example.test/connect'),
client: client,
);
addTearDown(session.dispose);
await session.start();
await flush();
final subscribe =
jsonDecode(channel.outgoing.single as String) as Map<String, dynamic>;
expect(session.subscription, RunSubscriptionState.pending);
channel.incoming.add(
jsonEncode({'id': subscribe['id'], 'type': 'subscribe'}),
);
await flush();
expect(session.subscription, RunSubscriptionState.live);
expect(session.subscriptionError, isEmpty);
session.resubscribe();
await flush();
final repeated =
jsonDecode(channel.outgoing.last as String) as Map<String, dynamic>;
expect(repeated['type'], 'subscribe');
channel.incoming.add(
jsonEncode({
'id': repeated['id'],
'type': 'error',
'error': 'too many run subscriptions on this connection',
}),
);
await flush();
expect(session.subscription, RunSubscriptionState.refused);
expect(session.subscriptionError, contains('too many run subscriptions'));
});
test('dispose drops the watch and releases the client', () async {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final session = AppSession(
endpoint: Uri.parse('ws://example.test/connect'),
client: client,
);
await session.start();
await flush();
session.dispose();
await flush();
expect(types(channel), ['subscribe', 'unsubscribe']);
await expectLater(
client.connect(Uri.parse('ws://example.test/connect')),
throwsStateError,
);
});
test('a missing endpoint is not replaced by a guessed connection', () async {
final channel = FakeChannel();
final client = PipelinesClient(channelFactory: (_) => channel);
final session = AppSession(endpoint: null, client: client);
addTearDown(session.dispose);
await session.start();
await flush();
expect(channel.outgoing, isEmpty);
expect(session.connected, isFalse);
});
}
@@ -0,0 +1,177 @@
import 'dart:convert';
import 'package:flutter/widgets.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 '../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) => channel
.outgoing
.map((frame) => jsonDecode(frame as String) as Map<String, dynamic>)
.where((frame) => frame['type'] == type)
.firstOrNull;
Future<void> pumpApp(
WidgetTester tester, {
required FakeChannel channel,
required PipelinesClient client,
required PlatformRouteInformationProvider provider,
}) async {
await tester.pumpWidget(
PipelinesApp(
server: webServer(),
client: client,
cupertino: false,
routeInformationProvider: provider,
),
);
await tester.pump();
}
Future<void> replyList(
WidgetTester tester,
FakeChannel channel, {
required List<Map<String, dynamic>> runs,
}) async {
for (
var attempt = 0;
attempt < 40 && requestOf(channel, 'list_runs') == null;
attempt++
) {
await tester.pump(const Duration(milliseconds: 5));
}
final request = requestOf(channel, 'list_runs')!;
channel.incoming.add(
jsonEncode({'id': request['id'], 'type': 'runs', 'runs': runs}),
);
await tester.pump();
await tester.pump();
}
Future<void> replyDetail(
WidgetTester tester,
FakeChannel channel,
num id,
) async {
for (
var attempt = 0;
attempt < 40 && requestOf(channel, 'get_run') == null;
attempt++
) {
await tester.pump(const Duration(milliseconds: 5));
}
final request = requestOf(channel, 'get_run')!;
expect(request['run_id'], id);
channel.incoming.add(
jsonEncode({
'id': request['id'],
'type': 'run',
'run_detail': {'id': id, 'title': 'Run $id', 'status': 'running'},
}),
);
await tester.pump();
await tester.pump();
}
void main() {
testWidgets('a /runs/1 boot link opens that run and Back returns to /runs', (
tester,
) async {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/runs/1')),
);
addTearDown(provider.dispose);
await pumpApp(tester, channel: channel, client: client, provider: provider);
await replyList(
tester,
channel,
runs: [
{'id': 1, 'name': 'Deep-linked run', 'status': 'running'},
],
);
await replyDetail(tester, channel, 1);
expect(find.text('Run 1'), findsWidgets);
expect(find.text('Back to list'), findsOneWidget);
expect(provider.value.uri.path, '/runs/1');
expect(find.text('Pipelines — Not implemented'), findsNothing);
await tester.tap(find.text('Back to list'));
await tester.pump();
expect(provider.value.uri.path, '/runs');
expect(find.text('Deep-linked run'), findsWidgets);
});
testWidgets('tabs and run selection update the route; browser Back pops it', (
tester,
) async {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')),
);
addTearDown(provider.dispose);
await pumpApp(tester, channel: channel, client: client, provider: provider);
expect(provider.value.uri.path, '/pipelines');
await tester.tap(find.text('Runs').last);
await tester.pump();
expect(provider.value.uri.path, '/runs');
await replyList(
tester,
channel,
runs: [
{'id': 2, 'name': 'Beta run', 'status': 'failed'},
],
);
await tester.tap(find.text('Beta run'));
await tester.pump();
expect(provider.value.uri.path, '/runs/2');
await replyDetail(tester, channel, 2);
expect(find.text('Back to list'), findsOneWidget);
// The engine's browser Back arrives as new route information.
await provider.didPushRouteInformation(
RouteInformation(uri: Uri.parse('/runs')),
);
await tester.pump();
expect(find.text('Beta run'), findsWidgets);
expect(find.text('Back to list'), findsNothing);
// Forward re-opens the same run.
await provider.didPushRouteInformation(
RouteInformation(uri: Uri.parse('/runs/2')),
);
await tester.pump();
await replyDetail(tester, channel, 2);
expect(find.text('Back to list'), findsOneWidget);
});
testWidgets('a malformed boot path is corrected to /pipelines', (
tester,
) async {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/runs/abc')),
);
addTearDown(provider.dispose);
await pumpApp(tester, channel: channel, client: client, provider: provider);
expect(provider.value.uri.path, '/pipelines');
expect(find.text('Pipelines — Not implemented'), findsOneWidget);
});
}
@@ -0,0 +1,302 @@
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/app_session.dart';
import 'package:pipelines_app/application/runs_destination.dart';
import 'package:pipelines_app/application/server_endpoint.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/runs/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,
);
Widget materialApp(
AppSession session,
ServerEndpoint server, {
int? initialRunId,
ValueChanged<int>? onRunSelected,
VoidCallback? onBack,
}) => MaterialApp(
home: Scaffold(
body: RunsDestination(
session: session,
server: server,
initialRunId: initialRunId,
onRunSelected: onRunSelected,
onBack: onBack,
),
),
);
Map<String, dynamic>? listRequest(FakeChannel channel) => channel.outgoing
.map((frame) => jsonDecode(frame as String) as Map<String, dynamic>)
.where((frame) => frame['type'] == 'list_runs')
.firstOrNull;
Iterable<Map<String, dynamic>> detailRequests(FakeChannel channel, int id) =>
channel.outgoing
.map((frame) => jsonDecode(frame as String) as Map<String, dynamic>)
.where((frame) => frame['type'] == 'get_run' && frame['run_id'] == id);
void main() {
testWidgets('gate explains missing native configuration without connecting', (
tester,
) async {
final channel = FakeChannel();
final client = PipelinesClient(channelFactory: (_) => channel);
final server = ServerEndpoint.resolve(
base: Uri.parse('http://127.0.0.1:8096/'),
web: false,
);
final session = AppSession(endpoint: server.uri, client: client);
addTearDown(session.dispose);
await tester.pumpWidget(materialApp(session, server));
expect(find.text('Server endpoint not configured'), findsOneWidget);
expect(find.textContaining('PIPELINES_SERVER_URL'), findsOneWidget);
expect(find.byType(RunsScreen), findsNothing);
expect(channel.outgoing, isEmpty);
});
testWidgets('gate shows connecting, then mounts the normal runs screen', (
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(materialApp(session, server));
await tester.pump();
expect(find.text('Connecting to Pipelines…'), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
expect(find.byType(RunsScreen), findsNothing);
channel.readyCompleter.complete();
await starting;
await tester.pump();
await tester.pump();
expect(find.byType(RunsScreen), findsOneWidget);
final list = listRequest(channel)!;
channel.incoming.add(
jsonEncode({
'id': list['id'],
'type': 'runs',
'runs': [
{'id': 5, 'name': 'Live fixture run', 'status': 'succeeded'},
],
}),
);
await tester.pump();
expect(find.text('Live fixture run'), findsOneWidget);
});
testWidgets('a refused socket shows a friendly reason, never the exception', (
tester,
) async {
final channel = FakeChannel();
final client = PipelinesClient(
channelFactory: (_) => channel,
backoffBase: const Duration(hours: 1),
backoffMax: const Duration(hours: 1),
);
final server = webServer();
final session = AppSession(endpoint: server.uri, client: client);
addTearDown(session.dispose);
final starting = session.start();
channel.readyCompleter.completeError(
StateError('WebSocketChannelException: Failed to connect'),
);
await starting;
await tester.pumpWidget(materialApp(session, server));
await tester.pump();
expect(find.text('Pipelines server unavailable'), findsOneWidget);
expect(find.textContaining('Retrying automatically'), findsOneWidget);
expect(find.textContaining('WebSocketChannelException'), findsNothing);
expect(find.widgetWithText(FilledButton, 'Retry'), findsOneWidget);
expect(find.byType(RunsScreen), findsNothing);
// The client keeps retrying by design; end the retry loop explicitly so
// the test does not leave a wall-clock timer behind.
session.dispose();
});
testWidgets(
'a drop keeps the list and reports reconnecting, not unavailable',
(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: 200),
);
final server = webServer();
final session = AppSession(endpoint: server.uri, client: client);
addTearDown(session.dispose);
await session.start();
await tester.pumpWidget(materialApp(session, server));
await tester.pump();
await tester.pump();
first.incoming.add(
jsonEncode({
'id': listRequest(first)!['id'],
'type': 'runs',
'runs': [
{'id': 1, 'name': 'Before reconnect', 'status': 'running'},
],
}),
);
await tester.pump();
expect(find.text('Before reconnect'), findsOneWidget);
first.incoming.addError(StateError('network drop'));
await tester.pump();
expect(find.byType(RunsScreen), findsOneWidget);
expect(find.text('Reconnecting to Pipelines…'), findsOneWidget);
expect(find.text('Pipelines server unavailable'), findsNothing);
expect(find.text('Before reconnect'), findsOneWidget);
for (
var attempt = 0;
attempt < 40 && listRequest(second) == null;
attempt++
) {
await tester.pump(const Duration(milliseconds: 50));
}
expect(listRequest(second), isNotNull);
expect(find.text('Reconnecting to Pipelines…'), findsNothing);
second.incoming.add(
jsonEncode({
'id': listRequest(second)!['id'],
'type': 'runs',
'runs': [
{'id': 2, 'name': 'After reconnect', 'status': 'succeeded'},
],
}),
);
await tester.pump();
expect(find.text('After reconnect'), findsOneWidget);
expect(find.text('Before reconnect'), findsNothing);
},
);
testWidgets(
'reconnect keeps the open detail instead of resetting to the list',
(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(materialApp(session, server, initialRunId: 1));
await tester.pump();
await tester.pump();
first.incoming.add(
jsonEncode({
'id': listRequest(first)!['id'],
'type': 'runs',
'runs': [
{'id': 1, 'name': 'Open run', 'status': 'running'},
],
}),
);
await tester.pump();
final firstDetail = detailRequests(first, 1).single;
first.incoming.add(
jsonEncode({
'id': firstDetail['id'],
'type': 'run',
'run_detail': {'id': 1, 'title': 'Open run', 'status': 'running'},
}),
);
await tester.pump();
expect(find.text('Open run'), findsOneWidget);
expect(find.text('Back to list'), findsOneWidget);
first.incoming.addError(StateError('network drop'));
await tester.pump();
expect(find.byType(RunsScreen), findsOneWidget);
expect(find.text('Open run'), findsOneWidget);
expect(find.text('Reconnecting to Pipelines…'), findsOneWidget);
for (
var attempt = 0;
attempt < 60 && listRequest(second) == null;
attempt++
) {
await tester.pump(const Duration(milliseconds: 10));
}
expect(listRequest(second), isNotNull);
second.incoming.add(
jsonEncode({
'id': listRequest(second)!['id'],
'type': 'runs',
'runs': [
{'id': 1, 'name': 'Open run', 'status': 'running'},
],
}),
);
for (
var attempt = 0;
attempt < 20 && detailRequests(second, 1).isEmpty;
attempt++
) {
await tester.pump(const Duration(milliseconds: 10));
}
final refreshed = detailRequests(second, 1).single;
expect(find.text('Open run'), findsOneWidget);
second.incoming.add(
jsonEncode({
'id': refreshed['id'],
'type': 'run',
'run_detail': {'id': 1, 'title': 'Open run', 'status': 'succeeded'},
}),
);
await tester.pump();
expect(find.text('Open run'), findsOneWidget);
expect(find.text('Back to list'), findsOneWidget);
},
);
testWidgets('gate uses Cupertino progress without a Material ancestor', (
tester,
) async {
final channel = FakeChannel();
final client = PipelinesClient(channelFactory: (_) => channel);
final server = webServer();
final session = AppSession(endpoint: server.uri, client: client);
addTearDown(session.dispose);
session.start();
await tester.pumpWidget(
CupertinoApp(
home: CupertinoPageScaffold(
child: RunsDestination(session: session, server: server),
),
),
);
await tester.pump();
expect(find.text('Connecting to Pipelines…'), findsOneWidget);
expect(find.byType(CupertinoActivityIndicator), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.byType(Material), findsNothing);
});
}
@@ -0,0 +1,61 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/server_endpoint.dart';
void main() {
test('web infers its own origin over ws at /connect', () {
final server = ServerEndpoint.resolve(
base: Uri.parse('http://127.0.0.1:8096/runs?filter=active'),
web: true,
);
expect(server.uri, Uri.parse('ws://127.0.0.1:8096/connect'));
expect(server.error, isNull);
expect(server.requiresConfiguration, isFalse);
});
test('secure web origin uses wss and the default port', () {
final server = ServerEndpoint.resolve(
base: Uri.parse('https://pipelines.example.test/runs'),
web: true,
);
expect(server.uri, Uri.parse('wss://pipelines.example.test/connect'));
});
test('web never guesses an endpoint when the page is not HTTP(S)', () {
final server = ServerEndpoint.resolve(
base: Uri.parse('file:///tmp/index.html'),
web: true,
);
expect(server.uri, isNull);
expect(server.error, contains('page URL'));
});
test('native requires an explicit endpoint instead of a baked host', () {
final server = ServerEndpoint.resolve(
base: Uri.parse('http://127.0.0.1:8096/'),
web: false,
);
expect(server.uri, isNull);
expect(server.requiresConfiguration, isTrue);
expect(server.error, isNull);
});
test('native validates and normalizes the configured endpoint', () {
final server = ServerEndpoint.resolve(
base: Uri.parse('http://127.0.0.1:8096/'),
web: false,
configured: ' ws://192.168.1.20:8081 ',
);
expect(server.uri, Uri.parse('ws://192.168.1.20:8081/connect'));
expect(server.requiresConfiguration, isFalse);
});
test('invalid native configuration reports the reason, never a fallback', () {
final server = ServerEndpoint.resolve(
base: Uri.parse('http://127.0.0.1:8096/'),
web: false,
configured: 'https://pipelines.example.test',
);
expect(server.uri, isNull);
expect(server.error, contains('Unsupported scheme'));
});
}
@@ -0,0 +1,86 @@
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/core/transport/pipelines_client.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
import 'pipelines_app_test.dart' show webServer, requestOf;
void main() {
for (final cupertino in [false, true]) {
testWidgets('Settings shares socket and one native bar ($cupertino)', (
tester,
) async {
SharedPreferences.setMockInitialValues({});
if (cupertino) {
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
}
final channel = FakeChannel()..readyCompleter.complete();
var sockets = 0;
final client = PipelinesClient(
channelFactory: (_) {
sockets++;
return channel;
},
);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')),
);
addTearDown(provider.dispose);
await tester.pumpWidget(
PipelinesApp(
server: webServer(),
client: client,
cupertino: cupertino,
routeInformationProvider: provider,
),
);
await tester.pump();
expect(
requestOf(channel, 'ping'),
isNull,
reason: 'Unvisited settings must not issue hidden requests',
);
await tester.tap(find.text('Settings').last);
await tester.pump();
await tester.pump();
expect(provider.value.uri.path, '/settings');
expect(find.text('Server URL'), findsOneWidget);
if (cupertino) {
final title = tester.widget<Text>(find.text('Connection'));
expect(
title.style!.color!.computeLuminance(),
greaterThan(0.5),
reason: 'Cupertino dark host must not inherit light Material text',
);
}
expect(find.text('Settings — Not implemented'), findsNothing);
expect(sockets, 1);
expect(
cupertino ? find.byType(CupertinoNavigationBar) : find.byType(AppBar),
findsOneWidget,
);
final ping = requestOf(channel, 'ping')!;
channel.incoming.add(
jsonEncode({
'id': ping['id'],
'type': 'pong',
'build': {'version': 'settings-fixture'},
'time': 'fixture time',
}),
);
await tester.pump();
await tester.pump();
expect(find.textContaining('settings-fixture'), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
}
}
@@ -0,0 +1,144 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'pipelines_client_test.dart' show FakeChannel;
Future<void> flush() => Future<void>.delayed(Duration.zero);
Map<String, dynamic> sent(FakeChannel channel, [int index = 0]) =>
jsonDecode(channel.outgoing[index] as String) as Map<String, dynamic>;
void reply(FakeChannel channel, {int index = 0, String type = 'pong'}) =>
channel.incoming.add(
jsonEncode({'id': sent(channel, index)['id'], 'type': type}),
);
void main() {
test(
'requests serialize through replies, errors do not poison queue',
() async {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
await client.connect(Uri.parse('ws://example.test'));
final first = client.call('ping');
final firstError = expectLater(first, throwsA(isA<ProtocolError>()));
final second = client.call('list_runs');
await flush();
expect(channel.outgoing, hasLength(1));
channel.incoming.add(
jsonEncode({
'id': sent(channel)['id'],
'type': 'error',
'error': 'refused',
}),
);
await firstError;
await flush();
expect(channel.outgoing, hasLength(2));
reply(channel, index: 1, type: 'runs');
expect((await second)['type'], 'runs');
await client.dispose();
},
);
test(
'timeout releases queue and late response is an unsolicited frame',
() async {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(
channelFactory: (_) => channel,
requestTimeout: const Duration(milliseconds: 10),
);
await client.connect(Uri.parse('ws://example.test'));
await expectLater(client.call('ping'), throwsA(isA<TimeoutException>()));
final late = client.frames.first;
reply(channel);
expect((await late)['type'], 'pong');
await client.dispose();
},
);
test(
'replacement fails queued calls rather than sending on new socket',
() async {
final channels = [
FakeChannel()..readyCompleter.complete(),
FakeChannel()..readyCompleter.complete(),
];
var index = 0;
final client = PipelinesClient(channelFactory: (_) => channels[index++]);
await client.connect(Uri.parse('ws://old.test'));
final firstError = expectLater(client.call('ping'), throwsStateError);
final queuedError = expectLater(
client.call('list_runs'),
throwsStateError,
);
await flush();
await client.connect(Uri.parse('ws://new.test'));
await Future.wait([firstError, queuedError]);
expect(channels.last.outgoing, isEmpty);
expect(client.state.kind, ConnectionKind.connected);
await client.dispose();
},
);
test('sendOnly never blocks correlated requests', () async {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
await client.connect(Uri.parse('ws://example.test'));
client.sendOnly('subscribe', {'workspace': ''});
final ping = client.call('ping');
await flush();
expect(sent(channel)['type'], 'subscribe');
reply(channel, index: 1);
expect((await ping)['type'], 'pong');
await client.dispose();
});
test('overlapping connect cannot create a superseded socket', () async {
var factories = 0;
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(
channelFactory: (_) {
factories++;
return channel;
},
);
await Future.wait([
client.connect(Uri.parse('ws://old.test')),
client.connect(Uri.parse('ws://new.test')),
]);
expect(factories, 1);
expect(client.state.kind, ConnectionKind.connected);
await client.dispose();
await expectLater(
client.connect(Uri.parse('ws://new.test')),
throwsStateError,
);
});
test('socket failure reconnects, disconnect cancels retry', () async {
final first = FakeChannel()..readyCompleter.complete();
final next = FakeChannel()..readyCompleter.complete();
var factories = 0;
final client = PipelinesClient(
channelFactory: (_) => factories++ == 0 ? first : next,
backoffBase: const Duration(milliseconds: 5),
);
await client.connect(Uri.parse('ws://example.test'));
final connectedAgain = client.states.firstWhere(
(s) => s.kind == ConnectionKind.connected,
);
first.incoming.addError(StateError('network drop'));
await connectedAgain.timeout(const Duration(seconds: 2));
expect(factories, 2);
await client.disconnect();
expect(client.state.retrying, isFalse);
expect(
() => client.sendOnly('subscribe'),
throwsA(isA<NotConnectedError>()),
);
await client.dispose();
});
}
@@ -0,0 +1,87 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
class FakeChannel implements WebSocketChannel {
final incoming = StreamController<dynamic>();
final outgoing = <dynamic>[];
final readyCompleter = Completer<void>();
@override
Stream<dynamic> get stream => incoming.stream;
@override
WebSocketSink get sink => FakeSink(outgoing, incoming);
@override
Future<void> get ready => readyCompleter.future;
@override
String? get protocol => null;
@override
int? get closeCode => null;
@override
String? get closeReason => null;
@override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class FakeSink implements WebSocketSink {
FakeSink(this.outgoing, this.incoming);
final List<dynamic> outgoing;
final StreamController<dynamic> incoming;
@override
void add(dynamic event) => outgoing.add(event);
@override
void addError(Object error, [StackTrace? stackTrace]) => throw error;
@override
Future<void> addStream(Stream<dynamic> stream) async {
await for (final item in stream) {
add(item);
}
}
@override
Future<void> close([int? closeCode, String? closeReason]) async {
await incoming.close();
}
@override
Future<void> get done async {}
@override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
void main() {
test('correlates replies and broadcasts unclaimed frames', () async {
final channel = FakeChannel();
final client = PipelinesClient(channelFactory: (_) => channel);
final frames = <Map<String, dynamic>>[];
client.frames.listen(frames.add);
final connecting = client.connect(Uri.parse('ws://example.test'));
channel.readyCompleter.complete();
await connecting;
final request = client.call('ping', {'value': 1});
await Future<void>.delayed(Duration.zero);
final sent =
jsonDecode(channel.outgoing.single as String) as Map<String, dynamic>;
channel.incoming.add(jsonEncode({'id': sent['id'], 'type': 'pong'}));
expect((await request)['type'], 'pong');
channel.incoming.add(jsonEncode({'type': 'run_event'}));
await Future<void>.delayed(Duration.zero);
expect(frames.single['type'], 'run_event');
await client.dispose();
});
test('disconnect fails pending requests', () async {
final channel = FakeChannel();
final client = PipelinesClient(channelFactory: (_) => channel);
final connecting = client.connect(Uri.parse('ws://example.test'));
channel.readyCompleter.complete();
await connecting;
final pending = client.call('ping');
await Future<void>.delayed(Duration.zero);
await client.disconnect();
await expectLater(pending, throwsA(isA<StateError>()));
await client.dispose();
});
}
@@ -0,0 +1,51 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/transport/server_url.dart';
void main() {
test('IPv6 authorities and encoded artifact queries stay intact', () {
expect(
ServerUrl.validate('ws://[::1]:8081').wsUrl,
'ws://[::1]:8081/connect',
);
expect(
ServerUrl.resolveArtifactUrl(
'ws://[::1]:8081/connect',
'/artifacts/a%20b?download=1',
).toString(),
'http://[::1]:8081/artifacts/a%20b?download=1',
);
expect(() => ServerUrl.validate('ws://host:70000'), throwsFormatException);
});
test('validates and normalizes endpoint with path and query', () {
final value = ServerUrl.validate(' wss://example.test:8443/?token=x ');
expect(value.wsUrl, 'wss://example.test:8443/connect?token=x');
expect(value.httpUrl, 'https://example.test:8443/connect?token=x');
expect(value.secure, isTrue);
});
test('rejects unsupported schemes and credentials', () {
expect(
() => ServerUrl.validate('https://example.test'),
throwsFormatException,
);
expect(
() => ServerUrl.validate('ws://user:pass@example.test'),
throwsFormatException,
);
});
test('resolves relative artifacts at the server origin', () {
expect(
ServerUrl.resolveArtifactUrl(
'ws://example.test:8081/connect',
'/artifacts/a',
)!.toString(),
'http://example.test:8081/artifacts/a',
);
expect(ServerUrl.resolveArtifactUrl('', '/artifacts/a'), isNull);
expect(
ServerUrl.resolveArtifactUrl('', 'https://cdn.test/a')!.toString(),
'https://cdn.test/a',
);
});
}
@@ -0,0 +1,241 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_capture.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_summary.dart';
import 'artifact_fixtures.dart';
void main() {
group('capture facts', () {
test('an absent or null artifact field is an unavailable capture', () {
final absent = ArtifactCapture.fromStep(step(includeArtifacts: false));
final explicitNull = ArtifactCapture.fromStep(step(artifacts: null));
expect(absent.availability, ArtifactCaptureAvailability.unavailable);
expect(absent.isAvailable, isFalse);
expect(absent.artifacts, isEmpty);
expect(explicitNull.isAvailable, isFalse);
});
test('a malformed artifact field is unavailable, not empty', () {
final capture = ArtifactCapture.fromStep(<String, dynamic>{
'artifacts': 'not a list',
});
expect(capture.isAvailable, isFalse);
expect(capture.artifacts, isEmpty);
});
test('an explicitly recorded empty list is an available empty capture', () {
final capture = ArtifactCapture.fromStep(step(artifacts: const []));
expect(capture.availability, ArtifactCaptureAvailability.recorded);
expect(capture.isAvailable, isTrue);
expect(capture.artifacts, isEmpty);
expect(capture.isPartial, isFalse);
});
test('records the skipped and truncated counts as capture facts', () {
final capture = ArtifactCapture.fromStep(
step(
artifacts: <Map<String, dynamic>>[artifact('shot.png')],
skipped: 4,
truncated: 7,
),
);
expect(capture.artifacts.length, 1);
expect(capture.skipped, 4);
expect(capture.truncated, 7);
expect(capture.isPartial, isTrue);
expect(
ArtifactCapture.fromStep(step(artifacts: const [])).isPartial,
isFalse,
);
});
});
group('run and visit wording', () {
test('a running or unavailable capture never claims no artifacts', () {
expect(
artifactsSummary(step(status: 'running', artifacts: null)),
'Artifacts · capture pending',
);
expect(
artifactsSummary(step(status: 'running', artifacts: const [])),
'Artifacts · capture pending',
);
expect(
artifactsSummary(step(status: 'completed', artifacts: null)),
'Artifacts · capture unavailable',
);
expect(
artifactsSummary(step(status: 'completed', includeArtifacts: false)),
'Artifacts · capture unavailable',
);
});
test(
'a finished available empty capture says not recorded for this visit',
() {
expect(
artifactsSummary(step(status: 'completed', artifacts: const [])),
'Artifacts · not recorded for this visit',
);
},
);
test('counts presented stage artifacts and flags partial capture', () {
final full = step(
artifacts: <Map<String, dynamic>>[
artifact('a.png'),
artifact('b.png'),
artifact('input.md'),
artifact('session.md'),
],
truncated: 1,
);
expect(
artifactsSummary(full),
'Artifacts · 2 recorded · partial capture',
);
expect(
artifactsSummary(
step(artifacts: <Map<String, dynamic>>[artifact('a.png')]),
),
'Artifacts · 1 recorded',
);
});
test(
'capture notes use the exact web wording and stay silent otherwise',
() {
final partial = step(
artifacts: <Map<String, dynamic>>[artifact('a.png')],
skipped: 4,
truncated: 7,
);
expect(artifactCaptureNotes(partial), <String>[
'4 files excluded from artifact capture.',
'7 files omitted by artifact capture limits.',
]);
expect(
artifactCaptureNotes(
step(
artifacts: <Map<String, dynamic>>[artifact('a.png')],
skipped: 2,
),
),
<String>['2 files excluded from artifact capture.'],
);
expect(
artifactCaptureNotes(
step(artifacts: <Map<String, dynamic>>[artifact('a.png')]),
),
isEmpty,
);
expect(
artifactCaptureNotes(step(artifacts: const [], skipped: 4)),
isEmpty,
);
expect(
artifactCaptureNotes(step(includeArtifacts: false, skipped: 4)),
isEmpty,
);
},
);
test('the run empty message keeps the web running wording', () {
expect(artifactsEmptyMessage(true), 'Artifacts · capture pending');
expect(
artifactsEmptyMessage(false),
'No artifacts recorded for this run.',
);
expect(
artifactsHeader(const [], executing: true),
'Artifacts · capture pending',
);
});
test(
'an unavailable run capture is not reported as no recorded artifacts',
() {
final steps = <Map<String, dynamic>>[
step(stage: 'planner', sequence: 1, artifacts: null),
step(stage: 'build', sequence: 2, artifacts: const []),
];
expect(
artifactsHeader(steps, executing: false),
'Artifacts · capture unavailable',
);
},
);
test('a fully available empty run says no artifacts were recorded', () {
final steps = <Map<String, dynamic>>[
step(stage: 'planner', sequence: 1, artifacts: const []),
step(stage: 'build', sequence: 2, artifacts: const []),
];
expect(
artifactsHeader(steps, executing: false),
'No artifacts recorded for this run.',
);
});
test(
'the run header counts exactly the gallery tiles, singular for one',
() {
final one = <Map<String, dynamic>>[
step(artifacts: <Map<String, dynamic>>[artifact('one.png')]),
];
expect(artifactsHeader(one, executing: false), 'Artifact · 1 recorded');
final four = <Map<String, dynamic>>[
step(
stage: 'planner',
sequence: 1,
artifacts: <Map<String, dynamic>>[
artifact('a.png'),
artifact('session.md'),
],
),
step(
stage: 'build',
sequence: 2,
artifacts: <Map<String, dynamic>>[
artifact('b.png'),
artifact('c.png'),
artifact('d.png'),
],
),
];
expect(
artifactsHeader(four, executing: false),
'Artifacts · 4 recorded',
);
expect(four, isNotEmpty);
},
);
test('partial capture is flagged on the run header', () {
final steps = <Map<String, dynamic>>[
step(artifacts: <Map<String, dynamic>>[artifact('a.png')], skipped: 2),
];
expect(
artifactsHeader(steps, executing: false),
'Artifact · 1 recorded · partial capture',
);
});
test('a visit that recorded only the retired session.md has no tile', () {
final steps = <Map<String, dynamic>>[
step(artifacts: <Map<String, dynamic>>[artifact('session.md')]),
];
expect(
artifactsHeader(steps, executing: false),
'No artifacts recorded for this run.',
);
expect(
artifactsSummary(steps.first),
'Artifacts · not recorded for this visit',
);
expect(artifactCaptureNotes(steps.first), isEmpty);
});
});
}
@@ -0,0 +1,44 @@
import 'package:pipelines_app/core/api_gateway.dart';
/// A minimal recorded [stage artifact], named so tests read like the web
/// client's fixtures. Every field the server records is present.
JsonMap artifact(
String name, {
String? url,
String contentType = '',
int sizeBytes = 0,
Map<String, dynamic> extra = const <String, dynamic>{},
}) {
return <String, dynamic>{
'name': name,
'url': url ?? '/artifacts/1/1/$name',
'content_type': contentType,
'size_bytes': sizeBytes,
...extra,
};
}
/// A minimal recorded step. [includeArtifacts] false omits the field entirely
/// (an unavailable capture); a null [artifacts] records an explicit null.
JsonMap step({
String stage = 'review',
int sequence = 1,
String status = 'completed',
int visit = 1,
List<JsonMap>? artifacts,
bool includeArtifacts = true,
int? skipped,
int? truncated,
List<JsonMap>? repairs,
}) {
return <String, dynamic>{
'stage': stage,
'sequence': sequence,
'status': status,
'control': <String, dynamic>{'visit': visit},
if (includeArtifacts) 'artifacts': artifacts,
'artifacts_skipped': ?skipped,
'artifacts_truncated': ?truncated,
'session_export_repairs': ?repairs,
};
}
@@ -0,0 +1,308 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_selection.dart';
import 'artifact_fixtures.dart';
void main() {
group('grouping', () {
test('groups interleaved steps by stage then recorded visit', () {
final steps = <Map<String, dynamic>>[
step(
stage: 'planner',
sequence: 1,
visit: 1,
artifacts: <Map<String, dynamic>>[artifact('a.png')],
),
step(
stage: 'build',
sequence: 2,
visit: 1,
artifacts: <Map<String, dynamic>>[artifact('b.png')],
),
step(
stage: 'planner',
sequence: 3,
visit: 2,
artifacts: <Map<String, dynamic>>[artifact('c.png')],
),
];
final groups = artifactGroups(steps);
expect(
groups.map((group) => '${group.stageKey}/${group.visit}'),
<String>['planner/1', 'planner/2', 'build/1'],
);
expect(groups.first.artifacts.map((record) => record.name), <String>[
'a.png',
]);
});
test('repeated stage visits stay separate and ordered by sequence', () {
final steps = <Map<String, dynamic>>[
step(
stage: 'review',
sequence: 7,
visit: 2,
artifacts: <Map<String, dynamic>>[artifact('second.md')],
),
step(
stage: 'review',
sequence: 3,
visit: 1,
artifacts: <Map<String, dynamic>>[artifact('first.md')],
),
];
final groups = artifactGroups(steps);
expect(groups.map((group) => group.visit), <int>[1, 2]);
expect(groups.map((group) => group.artifacts.single.name), <String>[
'first.md',
'second.md',
]);
});
test(
'a display visit is control.visit when positive, else position + 1',
() {
final steps = <Map<String, dynamic>>[
step(
stage: 's',
sequence: 1,
visit: 0,
artifacts: <Map<String, dynamic>>[artifact('a')],
),
step(
stage: 's',
sequence: 2,
visit: 0,
artifacts: <Map<String, dynamic>>[artifact('b')],
),
];
expect(artifactGroups(steps).map((group) => group.visit), <int>[1, 2]);
},
);
test('equal sequences keep recorded order', () {
final steps = <Map<String, dynamic>>[
step(
stage: 's',
sequence: 1,
visit: 1,
artifacts: <Map<String, dynamic>>[artifact('first')],
),
step(
stage: 's',
sequence: 1,
visit: 2,
artifacts: <Map<String, dynamic>>[artifact('second')],
),
];
expect(
artifactGroups(steps).map((group) => group.artifacts.single.name),
<String>['first', 'second'],
);
});
test('an absent stage visit is not fabricated', () {
final steps = <Map<String, dynamic>>[
step(
stage: 'a',
sequence: 1,
artifacts: <Map<String, dynamic>>[artifact('a.png')],
),
];
final groups = artifactGroups(steps);
expect(groups.single.stageKey, 'a');
expect(groups.any((group) => group.stageKey == 'b'), isFalse);
});
});
group('identity', () {
test('the same file name in different visits remains two groups', () {
final steps = <Map<String, dynamic>>[
step(
stage: 'implementer',
sequence: 1,
visit: 1,
artifacts: <Map<String, dynamic>>[
artifact('report.md', url: '/artifacts/1/1/report.md'),
],
),
step(
stage: 'implementer',
sequence: 2,
visit: 2,
artifacts: <Map<String, dynamic>>[
artifact('report.md', url: '/artifacts/1/2/report.md'),
],
),
];
final groups = artifactGroups(steps);
expect(groups.length, 2);
expect(groups.map((group) => group.artifacts.single.url), <String>[
'/artifacts/1/1/report.md',
'/artifacts/1/2/report.md',
]);
});
test('duplicate names in one visit are kept with their recorded urls', () {
final steps = <Map<String, dynamic>>[
step(
stage: 's',
sequence: 1,
artifacts: <Map<String, dynamic>>[
artifact('shot.png', url: '/artifacts/1/1/shot-a.png'),
artifact('shot.png', url: '/artifacts/1/1/shot-b.png'),
],
),
];
final artifacts = artifactGroups(steps).single.artifacts;
expect(artifacts.length, 2);
expect(artifacts.map((record) => record.url), <String>[
'/artifacts/1/1/shot-a.png',
'/artifacts/1/1/shot-b.png',
]);
});
test('the retired session.md is hidden but session.html is retained', () {
final steps = <Map<String, dynamic>>[
step(
stage: 's',
sequence: 1,
artifacts: <Map<String, dynamic>>[
artifact('session.md'),
artifact('session.html'),
artifact('report.md'),
],
),
];
// session.html is retained as system evidence, but neither it nor the
// retired session.md is stage output, so the gallery shows only the report.
expect(
artifactGroups(steps).single.artifacts.map((record) => record.name),
<String>['report.md'],
);
expect(
systemArtifacts(steps.single).map((record) => record.name),
<String>['session.html'],
);
});
});
group('shared public files', () {
test('a public file is attributed to the visit that first recorded it', () {
final steps = <Map<String, dynamic>>[
step(
stage: 'a',
sequence: 1,
artifacts: <Map<String, dynamic>>[
artifact('input.md'),
artifact('public/a.txt'),
],
),
step(
stage: 'b',
sequence: 2,
artifacts: <Map<String, dynamic>>[
artifact('output.md'),
artifact('public/a.txt'),
artifact('public/b.txt'),
],
),
];
final groups = artifactGroups(steps);
expect(
groups.map(
(group) => group.artifacts.map((record) => record.name).toList(),
),
<List<String>>[
<String>['public/a.txt'],
<String>['public/b.txt'],
],
);
expect(
visitArtifacts(steps[1], steps).map((record) => record.name),
<String>['public/b.txt'],
);
});
test(
'visitArtifacts keeps a repeated non-public name in a later visit',
() {
final steps = <Map<String, dynamic>>[
step(
stage: 'a',
sequence: 1,
artifacts: <Map<String, dynamic>>[
artifact('report.md', url: '/artifacts/1/1/report.md'),
],
),
step(
stage: 'a',
sequence: 2,
artifacts: <Map<String, dynamic>>[
artifact('report.md', url: '/artifacts/1/2/report.md'),
],
),
];
expect(
visitArtifacts(steps[1], steps).map((record) => record.url),
<String>['/artifacts/1/2/report.md'],
);
},
);
test('a public file repeated inside one visit is recorded once', () {
final steps = <Map<String, dynamic>>[
step(
stage: 'a',
sequence: 1,
artifacts: <Map<String, dynamic>>[
artifact('public/a.txt'),
artifact('public/a.txt'),
],
),
];
expect(artifactGroups(steps).single.artifacts.length, 1);
});
});
group('unavailable and empty captures', () {
test('unavailable, null and empty visits yield no group', () {
final steps = <Map<String, dynamic>>[
step(stage: 'a', sequence: 1, includeArtifacts: false),
step(stage: 'a', sequence: 2, artifacts: null),
step(stage: 'a', sequence: 3, artifacts: const []),
step(
stage: 'b',
sequence: 4,
artifacts: <Map<String, dynamic>>[artifact('only.png')],
),
];
final groups = artifactGroups(steps);
expect(groups.length, 1);
expect(groups.single.stageKey, 'b');
expect(groups.single.visit, 1);
});
test('a visit with only utility or retired files yields no group', () {
final steps = <Map<String, dynamic>>[
step(
stage: 'a',
sequence: 1,
artifacts: <Map<String, dynamic>>[
artifact('input.md'),
artifact('session.md'),
artifact('session.html'),
],
),
];
expect(artifactGroups(steps), isEmpty);
});
test('an empty run yields no groups', () {
expect(artifactGroups(const []), isEmpty);
});
});
}
@@ -0,0 +1,110 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_kind.dart';
void main() {
test('classifies images and videos from their recorded content type', () {
expect(artifactKind('image/png', 'shot.png'), ArtifactKind.image);
expect(
artifactKind('image/svg+xml; charset=utf-8', 'plot'),
ArtifactKind.image,
);
expect(artifactKind('video/mp4', 'clip.mp4'), ArtifactKind.video);
});
test('matches the web client file-kind vocabulary by MIME and name', () {
const cases = <(String, String, ArtifactKind)>[
('audio/mpeg', 'sound.mp3', ArtifactKind.audio),
('application/pdf', 'report', ArtifactKind.pdf),
('application/octet-stream', 'data.pdf', ArtifactKind.pdf),
('application/json', 'payload', ArtifactKind.json),
('text/plain', 'config.json', ArtifactKind.json),
('application/zip', 'bundle', ArtifactKind.archive),
('text/plain', 'backup.tar.gz', ArtifactKind.archive),
('text/csv', 'rows', ArtifactKind.spreadsheet),
('application/octet-stream', 'sheet.xlsx', ArtifactKind.spreadsheet),
('text/plain', 'run.log', ArtifactKind.log),
('application/xml', 'layout', ArtifactKind.code),
('text/plain', 'main.go', ArtifactKind.code),
('text/html; charset=utf-8', 'session.html', ArtifactKind.document),
('text/plain', 'notes.txt', ArtifactKind.document),
('application/octet-stream', 'blob.bin', ArtifactKind.other),
('', '', ArtifactKind.other),
('application/x-unknown-thing', 'report.unknownext', ArtifactKind.other),
];
for (final (contentType, name, kind) in cases) {
expect(
artifactKind(contentType, name),
kind,
reason: '$contentType $name',
);
}
});
test('names every kind in prose, with File as the unknown fallback', () {
expect(artifactKindLabel(ArtifactKind.image), 'Image');
expect(artifactKindLabel(ArtifactKind.video), 'Video');
expect(artifactKindLabel(ArtifactKind.audio), 'Audio');
expect(artifactKindLabel(ArtifactKind.pdf), 'PDF');
expect(artifactKindLabel(ArtifactKind.json), 'JSON');
expect(artifactKindLabel(ArtifactKind.archive), 'Archive');
expect(artifactKindLabel(ArtifactKind.spreadsheet), 'Spreadsheet');
expect(artifactKindLabel(ArtifactKind.log), 'Log');
expect(artifactKindLabel(ArtifactKind.code), 'Code');
expect(artifactKindLabel(ArtifactKind.document), 'Document');
expect(artifactKindLabel(ArtifactKind.other), 'File');
});
test('formats recorded bytes like the web client', () {
expect(humanBytes(0), '0 B');
expect(humanBytes(999), '999 B');
expect(humanBytes(1024), '1.0 KiB');
expect(humanBytes(1536), '1.5 KiB');
expect(humanBytes(2 * 1024 * 1024), '2.0 MiB');
expect(humanBytes(3 * 1024 * 1024 * 1024), '3.0 GiB');
});
test('markdown and viewer artifacts use the shared classification', () {
const markdown = <(String, String)>[
('text/markdown', 'plan'),
('text/markdown; charset=utf-8', 'plan'),
('text/plain', 'notes'),
('application/octet-stream', 'input.md'),
('', 'memory.markdown'),
('', 'output.txt'),
];
for (final (contentType, name) in markdown) {
expect(isMarkdownArtifact(contentType, name), isTrue, reason: name);
}
for (final (contentType, name) in <(String, String)>[
('text/html', 'session.html'),
('text/csv', 'rows.csv'),
('application/json', 'payload.json'),
('text/x-python', 'main.py'),
('application/xml', 'shot.png.xml'),
('', ''),
]) {
expect(isMarkdownArtifact(contentType, name), isFalse, reason: name);
}
for (final (contentType, name) in <(String, String)>[
('image/png', 'shot.png'),
('video/mp4', 'clip.mp4'),
('text/markdown', 'input.md'),
('text/plain', 'memory.txt'),
('', 'output.md'),
]) {
expect(isViewerArtifact(contentType, name), isTrue, reason: name);
}
for (final (contentType, name) in <(String, String)>[
('text/html', 'session.html'),
('text/csv', 'rows.csv'),
('application/json', 'payload.json'),
('text/x-python', 'main.py'),
('text/plain', 'run.log'),
('application/octet-stream', 'blob.bin'),
('', ''),
]) {
expect(isViewerArtifact(contentType, name), isFalse, reason: name);
}
});
}
@@ -0,0 +1,154 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_selection.dart';
import 'artifact_fixtures.dart';
void main() {
group('record preservation', () {
test('keeps size, content type, url and unknown fields verbatim', () {
final recorded = ArtifactRecord.fromJson(
artifact(
'shot.png',
url: '/artifacts/7/3/shot.png',
contentType: 'image/png',
sizeBytes: 1536,
extra: <String, dynamic>{
'sha256': 'abc',
'capture': <String, dynamic>{'source': 'stage'},
},
),
);
expect(recorded.name, 'shot.png');
expect(recorded.url, '/artifacts/7/3/shot.png');
expect(recorded.contentType, 'image/png');
expect(recorded.sizeBytes, 1536);
expect(recorded.raw['sha256'], 'abc');
expect((recorded.raw['capture'] as Map)['source'], 'stage');
});
test('never invents a missing name, url, type or size', () {
final recorded = ArtifactRecord.fromJson(const <String, dynamic>{});
expect(recorded.name, '');
expect(recorded.url, '');
expect(recorded.contentType, '');
expect(recorded.sizeBytes, 0);
expect(recorded.hasUrl, isFalse);
});
test('the raw record is read-only, including nested values', () {
final recorded = ArtifactRecord.fromJson(
artifact(
'a.txt',
extra: <String, dynamic>{
'nested': <String, dynamic>{'x': 1},
},
),
);
expect(
() => recorded.raw['nested'] = <String, dynamic>{},
throwsUnsupportedError,
);
expect(
() => (recorded.raw['nested'] as Map)['x'] = 2,
throwsUnsupportedError,
);
});
});
group('retired and utility files', () {
test(
'hides session.md from presented artifacts but keeps session.html',
() {
final records = <ArtifactRecord>[
ArtifactRecord.fromJson(artifact('shot.png')),
ArtifactRecord.fromJson(artifact(legacySessionMarkdownArtifact)),
ArtifactRecord.fromJson(artifact('session.html')),
];
expect(
presentedArtifacts(records).map((record) => record.name),
<String>['shot.png', 'session.html'],
);
},
);
test('utility files are system evidence, not stage output', () {
expect(systemArtifactNames, <String>[
'input.md',
'memory.md',
'output.md',
'session.html',
]);
for (final name in systemArtifactNames) {
expect(isSystemArtifactName(name), isTrue, reason: name);
}
expect(isSystemArtifactName('public/input.md'), isFalse);
expect(isSystemArtifactName('session.md'), isFalse);
expect(isSystemArtifactName('shot.png'), isFalse);
});
test('stage artifacts exclude utility files and repair exports', () {
final recorded = step(
artifacts: <dynamic>[
artifact('input.md'),
artifact('memory.md'),
artifact('output.md'),
artifact('session.html'),
artifact('repaired.html'),
artifact('public/input.md'),
artifact('shot.png'),
].cast<Map<String, dynamic>>(),
repairs: <Map<String, dynamic>>[
<String, dynamic>{'html': 'repaired.html'},
],
);
expect(stageArtifacts(recorded).map((record) => record.name), <String>[
'public/input.md',
'shot.png',
]);
expect(systemArtifacts(recorded).map((record) => record.name), <String>[
'input.md',
'memory.md',
'output.md',
'session.html',
'repaired.html',
]);
});
test('a missing or malformed artifact list records no artifacts', () {
expect(artifactsOf(step(includeArtifacts: false)), isEmpty);
expect(artifactsOf(step(artifacts: null)), isEmpty);
expect(artifactsOf(step(artifacts: const [])), isEmpty);
expect(
artifactsOf(<String, dynamic>{'artifacts': 'not a list'}),
isEmpty,
);
});
test('duplicate names are records, not identities to dedupe', () {
final records = <ArtifactRecord>[
ArtifactRecord.fromJson(
artifact('shot.png', url: '/artifacts/1/1/a.png'),
),
ArtifactRecord.fromJson(
artifact('shot.png', url: '/artifacts/1/1/b.png'),
),
];
expect(
stageArtifacts(
step(
artifacts: <Map<String, dynamic>>[
artifact('shot.png', url: '/artifacts/1/1/a.png'),
artifact('shot.png', url: '/artifacts/1/1/b.png'),
],
),
).map((record) => record.url),
<String>['/artifacts/1/1/a.png', '/artifacts/1/1/b.png'],
);
expect(records.length, 2);
});
});
}
@@ -0,0 +1,148 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_url.dart';
void main() {
group('server-relative paths', () {
test(
'resolve against the configured endpoint origin, dropping its path',
() {
final resolved = resolveArtifactUrl(
'ws://example.test:8081/connect?token=x',
'/artifacts/a%20b?download=1',
);
expect(resolved, isNotNull);
expect(
resolved!.uri.toString(),
'http://example.test:8081/artifacts/a%20b?download=1',
);
expect(resolved.external, isFalse);
},
);
test('map wss to https and omit the default port', () {
final resolved = resolveArtifactUrl(
'wss://example.test/connect',
'artifacts/shot.png',
);
expect(
resolved!.uri.toString(),
'https://example.test/artifacts/shot.png',
);
expect(resolved.external, isFalse);
});
test('keep IPv6 brackets and encoded paths intact', () {
final resolved = resolveArtifactUrl(
'ws://[::1]:8081/connect',
'/artifacts/a%2Fb?next=%2Fnext',
);
expect(
resolved!.uri.toString(),
'http://[::1]:8081/artifacts/a%2Fb?next=%2Fnext',
);
expect(resolved.uri.host, '::1');
});
test('a blank endpoint leaves a relative artifact unresolved', () {
expect(resolveArtifactUrl('', '/artifacts/a'), isNull);
expect(resolveArtifactUrl('not a url', '/artifacts/a'), isNull);
expect(
resolveArtifactUrl('https://example.test', '/artifacts/a'),
isNull,
);
});
});
group('absolute http(s) artifacts', () {
test('a same-origin absolute url stays internal', () {
final resolved = resolveArtifactUrl(
'ws://example.test:8081/connect',
'http://example.test:8081/artifacts/a%20b?download=1',
);
expect(
resolved!.uri.toString(),
'http://example.test:8081/artifacts/a%20b?download=1',
);
expect(resolved.external, isFalse);
});
test('cross-host, cross-port and cross-scheme urls are external', () {
const configured = 'wss://example.test/connect';
for (final url in <String>[
'https://cdn.test/artifacts/a',
'https://example.test:8443/artifacts/a',
'http://example.test/artifacts/a',
]) {
final resolved = resolveArtifactUrl(configured, url);
expect(resolved, isNotNull, reason: url);
expect(resolved!.external, isTrue, reason: url);
}
});
test('an absolute url without a usable configured origin is external', () {
final resolved = resolveArtifactUrl('', 'https://cdn.test/a%2Fb?q=1');
expect(resolved!.uri.toString(), 'https://cdn.test/a%2Fb?q=1');
expect(resolved.external, isTrue);
});
});
group('unsafe urls', () {
test('rejects blank, protocol-relative and hostless urls', () {
for (final url in <String>[
'',
' ',
'//evil.test/artifacts/a',
'http:///artifacts/a',
'http://',
'https://?x=1',
]) {
expect(
resolveArtifactUrl('ws://example.test:8081', url),
isNull,
reason: url,
);
}
});
test('rejects credentials in any absolute url', () {
for (final url in <String>[
'http://user:pass@example.test/artifacts/a',
'https://user@example.test/artifacts/a',
'http://example.test:8081@evil.test/artifacts/a',
]) {
expect(
resolveArtifactUrl('ws://example.test:8081', url),
isNull,
reason: url,
);
}
});
test('rejects unsafe and non-http schemes', () {
for (final url in <String>[
'javascript:alert(1)',
'data:text/html,hello',
'file:///etc/passwd',
'ftp://example.test/a',
'intent://example.test/a#Intent;end',
'mailto:ops@example.test',
]) {
expect(
resolveArtifactUrl('ws://example.test:8081', url),
isNull,
reason: url,
);
}
});
test('never produces a non-http(s) output', () {
final resolved = resolveArtifactUrl(
'ws://example.test:8081/connect',
'/artifacts/a',
);
expect(resolved!.uri.scheme, 'http');
expect(resolved.uri.hasAuthority, isTrue);
expect(resolved.uri.userInfo, isEmpty);
});
});
}
@@ -0,0 +1,197 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
import 'package:pipelines_app/features/artifacts/domain/gallery_navigation.dart';
import 'artifact_fixtures.dart';
ArtifactRecord record(String name, {String contentType = '', String? url}) =>
ArtifactRecord.fromJson(artifact(name, contentType: contentType, url: url));
void main() {
group('filtered gallery order', () {
test('pages viewer artifacts group by group, in recorded order', () {
final groups = <ArtifactGroup>[
ArtifactGroup(
stageKey: 'reviewer',
visit: 1,
artifacts: <ArtifactRecord>[
record('session.html', contentType: 'text/html'),
record('input.md', contentType: 'text/markdown'),
],
),
ArtifactGroup(
stageKey: 'implementer',
visit: 2,
artifacts: <ArtifactRecord>[
record('run.log', contentType: 'text/plain'),
record('shot.png', contentType: 'image/png'),
record('main.py', contentType: 'text/x-python'),
record('clip.mp4', contentType: 'video/mp4'),
record('memory.txt', contentType: 'text/plain'),
record('rows.csv', contentType: 'text/csv'),
record('output.md', contentType: 'application/octet-stream'),
],
),
];
expect(pagedArtifacts(groups).map((page) => page.artifact.name), <String>[
'input.md',
'shot.png',
'clip.mp4',
'memory.txt',
'output.md',
]);
expect(pagedArtifacts(const []), isEmpty);
});
test('a page keeps the stage visit it belongs to', () {
final groups = artifactGroups(<Map<String, dynamic>>[
step(
stage: 'a',
sequence: 1,
visit: 3,
artifacts: <Map<String, dynamic>>[
artifact('a.png', contentType: 'image/png'),
],
),
step(
stage: 'b',
sequence: 2,
visit: 5,
artifacts: <Map<String, dynamic>>[
artifact('b.png', contentType: 'image/png'),
],
),
]);
final pages = pagedArtifacts(groups);
expect(pages.map((page) => '${page.stageKey}/${page.visit}'), <String>[
'a/3',
'b/5',
]);
expect(pages.map((page) => page.pageIndex), <int>[0, 1]);
});
});
group('identity', () {
test('duplicate names with different urls get distinct viewer indices', () {
final groups = artifactGroups(<Map<String, dynamic>>[
step(
stage: 'a',
sequence: 1,
visit: 1,
artifacts: <Map<String, dynamic>>[
artifact(
'shot.png',
url: '/artifacts/1/1/shot.png',
contentType: 'image/png',
),
],
),
step(
stage: 'a',
sequence: 2,
visit: 2,
artifacts: <Map<String, dynamic>>[
artifact(
'shot.png',
url: '/artifacts/1/2/shot.png',
contentType: 'image/png',
),
],
),
]);
final index = viewerIndexByUrl(groups);
expect(index, <String, int>{
'/artifacts/1/1/shot.png': 0,
'/artifacts/1/2/shot.png': 1,
});
expect(pagedArtifacts(groups).map((page) => page.identity), <String>[
'/artifacts/1/1/shot.png',
'/artifacts/1/2/shot.png',
]);
});
test('a repeated url maps to its first occurrence only', () {
final groups = artifactGroups(<Map<String, dynamic>>[
step(
stage: 'a',
sequence: 1,
artifacts: <Map<String, dynamic>>[
artifact(
'a.png',
url: '/artifacts/1/1/a.png',
contentType: 'image/png',
),
artifact(
'a.png',
url: '/artifacts/1/1/a.png',
contentType: 'image/png',
),
],
),
]);
final index = viewerIndexByUrl(groups);
expect(index, <String, int>{'/artifacts/1/1/a.png': 0});
expect(pagedArtifacts(groups).length, 2);
});
test('artifacts without a url keep distinct fallback identities', () {
final groups = artifactGroups(<Map<String, dynamic>>[
step(
stage: 'a',
sequence: 1,
visit: 2,
artifacts: <Map<String, dynamic>>[
artifact('shot.png', url: '', contentType: 'image/png'),
artifact('shot.png', url: '', contentType: 'image/png'),
],
),
]);
final pages = pagedArtifacts(groups);
expect(pages.map((page) => page.identity).toSet().length, 2);
expect(viewerIndexByUrl(groups), isEmpty);
});
test('non-viewer artifacts never get a viewer identity', () {
final groups = artifactGroups(<Map<String, dynamic>>[
step(
stage: 'a',
sequence: 1,
artifacts: <Map<String, dynamic>>[
artifact('session.html', contentType: 'text/html'),
artifact('main.py', contentType: 'text/x-python'),
artifact('run.log', contentType: 'text/plain'),
],
),
]);
expect(pagedArtifacts(groups), isEmpty);
expect(viewerIndexByUrl(groups), isEmpty);
});
});
group('paging', () {
test('previous and next clamp at both ends without wrapping', () {
expect(pagedIndex(0, -1, 3), 0);
expect(pagedIndex(1, -1, 3), 0);
expect(pagedIndex(1, 1, 3), 2);
expect(pagedIndex(2, 1, 3), 2);
expect(pagedIndex(0, 0, 0), 0);
expect(pagedIndex(0, 0, 1), 0);
expect(pagedIndex(9, -3, 0), 0);
});
test('the position label trims the content type and falls back', () {
expect(
artifactViewerPositionLabel(0, 3, 'image/png'),
'1 of 3 · image/png',
);
expect(
artifactViewerPositionLabel(1, 3, 'image/png; charset=binary'),
'2 of 3 · image/png',
);
expect(artifactViewerPositionLabel(4, 5, ''), '5 of 5 · artifact');
expect(artifactViewerPositionLabel(0, 1, ' '), '1 of 1 · artifact');
});
});
}
@@ -0,0 +1,87 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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_visit_list.dart';
import '../domain/artifact_fixtures.dart';
/// A recorded name long enough to wrap at large text sizes.
const longArtifactName =
'a-very-long-recorded-artifact-file-name-that-must-wrap-across-'
'several-lines-at-large-text-sizes.csv';
/// The non-breaking space the row inserts between a size value and its unit.
const nonBreakingSpace = '\u00a0';
/// One recorded artifact. An empty [url] falls back to the fixture's url; use
/// [unaddressedArtifact] for a record the server sent without one.
ArtifactRecord recordedArtifact(
String name, {
String url = '',
String contentType = '',
int sizeBytes = 0,
}) {
return ArtifactRecord.fromJson(
artifact(
name,
url: url.isEmpty ? null : url,
contentType: contentType,
sizeBytes: sizeBytes,
),
);
}
/// A record with no recorded url or content type, never completed locally.
///
/// [name] defaults to empty, so the record is otherwise entirely unaddressed.
ArtifactRecord unaddressedArtifact({String name = ''}) {
return ArtifactRecord.fromJson(<String, dynamic>{
'name': name,
'url': '',
'content_type': '',
'size_bytes': 0,
});
}
ArtifactGroup visitGroup({
String stageKey = 'review',
int visit = 1,
List<ArtifactRecord> artifacts = const <ArtifactRecord>[],
}) {
return ArtifactGroup(stageKey: stageKey, visit: visit, artifacts: artifacts);
}
/// The list under the native host it is composed into, with the optional
/// grouped page colour a gallery must supply.
Widget artifactListHost({
required bool cupertino,
required List<ArtifactGroup> groups,
String? selectedIdentity,
ArtifactSelected? onSelected,
double textScale = 1,
}) {
final list = ArtifactVisitList(
groups: groups,
selectedIdentity: selectedIdentity,
onSelected: onSelected,
);
Widget scaled(BuildContext context, Widget? child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child ?? const SizedBox.shrink(),
);
return cupertino
? CupertinoApp(
builder: scaled,
home: CupertinoPageScaffold(
backgroundColor: CupertinoColors.systemGroupedBackground,
child: list,
),
)
: MaterialApp(
builder: scaled,
home: Scaffold(body: list),
);
}
@@ -0,0 +1,170 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart';
import 'artifact_visit_list_fixture.dart';
List<ArtifactGroup> _threeGroups() => [
visitGroup(
stageKey: 'build',
visit: 1,
artifacts: [
recordedArtifact(longArtifactName, url: '/artifacts/7/3/long.xlsx'),
],
),
visitGroup(
visit: 1,
artifacts: [
recordedArtifact('result.csv', url: '/artifacts/7/1/result.csv'),
recordedArtifact('notes.md', url: '/artifacts/7/1/notes.md'),
],
),
visitGroup(
visit: 2,
artifacts: [
recordedArtifact('result.csv', url: '/artifacts/7/2/result.csv'),
],
),
];
void main() {
testWidgets('every group heading is a header node under both hosts', (
tester,
) async {
final handle = tester.ensureSemantics();
for (final cupertino in <bool>[false, true]) {
await tester.pumpWidget(
artifactListHost(cupertino: cupertino, groups: _threeGroups()),
);
for (final label in <String>[
'build · visit 1',
'review · visit 1',
'review · visit 2',
]) {
expect(
tester.getSemantics(find.text(label)),
isSemantics(label: label, isHeader: true),
reason:
'${cupertino ? 'Cupertino' : 'Material'} must expose $label as a '
'heading',
);
}
}
handle.dispose();
});
testWidgets('a Cupertino heading stays separate from its single row', (
tester,
) async {
final handle = tester.ensureSemantics();
final group = visitGroup(
visit: 2,
artifacts: [
recordedArtifact(
'result.csv',
url: '/artifacts/7/2/result.csv',
contentType: 'text/csv',
sizeBytes: 4096,
),
],
);
await tester.pumpWidget(
artifactListHost(cupertino: true, groups: [group], onSelected: (_, _) {}),
);
final heading = tester.getSemantics(find.text('review · visit 2'));
expect(heading, isSemantics(label: 'review · visit 2', isHeader: true));
expect(
heading.getSemanticsData().hasAction(SemanticsAction.tap),
isFalse,
reason: 'a heading must never activate the artifact below it',
);
final button = tester.getSemantics(find.byType(CupertinoButton));
expect(button, isSemantics(isButton: true, hasTapAction: true));
expect(button.label, contains('result.csv'));
expect(
button.label,
isNot(contains('review · visit 2')),
reason: 'the row accessible name must not repeat the group heading',
);
final headingRect = tester.getRect(find.text('review · visit 2'));
final rowRect = tester.getRect(find.byType(CupertinoButton));
expect(
rowRect.top,
greaterThanOrEqualTo(headingRect.bottom),
reason: 'the row must not cover the heading',
);
handle.dispose();
});
testWidgets('rows without a callback expose no tap action under both hosts', (
tester,
) async {
final handle = tester.ensureSemantics();
final group = visitGroup(
artifacts: [
recordedArtifact('result.csv', url: '/artifacts/7/1/result.csv'),
],
);
for (final cupertino in <bool>[false, true]) {
await tester.pumpWidget(
artifactListHost(cupertino: cupertino, groups: [group]),
);
final row = tester.getSemantics(find.text('result.csv'));
expect(
row.getSemanticsData().hasAction(SemanticsAction.tap),
isFalse,
reason: 'without onSelected the row is read-only',
);
expect(
row,
isSemantics(isButton: false),
reason: 'a read-only row must not expose a button role',
);
await tester.tap(find.text('result.csv'));
expect(tester.takeException(), isNull);
}
handle.dispose();
});
testWidgets('the selected row carries the selected semantics state', (
tester,
) async {
final handle = tester.ensureSemantics();
final first = visitGroup(
visit: 1,
artifacts: [recordedArtifact('result.csv', url: '/artifacts/7/1/a.csv')],
);
final second = visitGroup(
visit: 2,
artifacts: [recordedArtifact('result.csv', url: '/artifacts/7/2/b.csv')],
);
await tester.pumpWidget(
artifactListHost(
cupertino: true,
groups: [first, second],
selectedIdentity: artifactVisitIdentity(
second,
second.artifacts.single,
),
onSelected: (_, _) {},
),
);
expect(
tester.getSemantics(find.text('result.csv').last),
isSemantics(isSelected: true),
);
expect(
tester.getSemantics(find.text('result.csv').first),
isSemantics(isSelected: false),
);
handle.dispose();
});
}
@@ -0,0 +1,230 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.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_visit_list.dart';
import 'artifact_visit_list_fixture.dart';
void main() {
test('a shared filename in two visits has distinct identities', () {
const url = '/artifacts/7/result.csv';
final first = visitGroup(
visit: 1,
artifacts: [
recordedArtifact('result.csv', url: url, contentType: 'text/csv'),
],
);
final second = visitGroup(
visit: 2,
artifacts: [
recordedArtifact('result.csv', url: url, contentType: 'text/csv'),
],
);
expect(
artifactVisitIdentity(first, first.artifacts.single),
isNot(artifactVisitIdentity(second, second.artifacts.single)),
);
expect(
artifactVisitIdentity(first, first.artifacts.single),
artifactVisitIdentity(first, first.artifacts.single),
);
});
test('an unaddressed record is identified by its recorded name', () {
final addressed = visitGroup(
visit: 1,
artifacts: [
recordedArtifact('result.csv', url: '/artifacts/7/1/result.csv'),
],
);
final unaddressed = visitGroup(
visit: 1,
artifacts: [unaddressedArtifact(name: 'result.csv')],
);
expect(
artifactVisitIdentity(unaddressed, unaddressed.artifacts.single),
'review\u00001\u0000result.csv',
);
expect(
artifactVisitIdentity(unaddressed, unaddressed.artifacts.single),
isNot(artifactVisitIdentity(addressed, addressed.artifacts.single)),
);
});
testWidgets('Material rows show recorded visit, MIME and size', (
tester,
) async {
final first = visitGroup(
visit: 1,
artifacts: [
recordedArtifact(
'result.csv',
url: '/artifacts/7/1/result.csv',
contentType: 'text/csv',
sizeBytes: 2048,
),
],
);
final second = visitGroup(
visit: 2,
artifacts: [
recordedArtifact(
'result.csv',
url: '/artifacts/7/2/result.csv',
contentType: 'text/csv; charset=utf-8',
sizeBytes: 4096,
),
],
);
ArtifactGroup? pickedGroup;
ArtifactRecord? pickedArtifact;
await tester.pumpWidget(
artifactListHost(
cupertino: false,
groups: [first, second],
selectedIdentity: artifactVisitIdentity(
second,
second.artifacts.single,
),
onSelected: (selectedGroup, selectedArtifact) {
pickedGroup = selectedGroup;
pickedArtifact = selectedArtifact;
},
),
);
expect(find.text('review · visit 1'), findsOneWidget);
expect(find.text('review · visit 2'), findsOneWidget);
expect(find.text('result.csv'), findsNWidgets(2));
expect(find.text('text/csv · 2.0${nonBreakingSpace}KiB'), findsOneWidget);
expect(find.text('text/csv · 4.0${nonBreakingSpace}KiB'), findsOneWidget);
expect(find.byIcon(Icons.check), findsOneWidget);
await tester.tap(find.text('result.csv').first);
expect(pickedGroup, same(first));
expect(pickedArtifact, same(first.artifacts.single));
await tester.tap(find.text('result.csv').last);
expect(pickedGroup, same(second));
expect(pickedArtifact!.url, '/artifacts/7/2/result.csv');
});
testWidgets('Cupertino uses grouped native controls and selects per visit', (
tester,
) async {
final first = visitGroup(
visit: 1,
artifacts: [
recordedArtifact('result.csv', url: '/artifacts/7/1/result.csv'),
],
);
final second = visitGroup(
visit: 2,
artifacts: [
recordedArtifact('result.csv', url: '/artifacts/7/2/result.csv'),
],
);
ArtifactGroup? pickedGroup;
await tester.pumpWidget(
artifactListHost(
cupertino: true,
groups: [first, second],
selectedIdentity: artifactVisitIdentity(first, first.artifacts.single),
onSelected: (selectedGroup, _) => pickedGroup = selectedGroup,
),
);
expect(find.byType(CupertinoListSection), findsNWidgets(2));
expect(find.byType(CupertinoButton), findsNWidgets(2));
expect(find.byType(ListTile), findsNothing);
expect(find.byIcon(CupertinoIcons.check_mark), findsOneWidget);
await tester.tap(find.text('result.csv').last);
expect(pickedGroup, same(second));
});
testWidgets('long names wrap at 2x under both native hosts', (tester) async {
tester.view.devicePixelRatio = 2;
tester.view.physicalSize = const Size(780, 1560);
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final withLongName = visitGroup(
visit: 3,
artifacts: [
recordedArtifact(
longArtifactName,
url: '/artifacts/7/3/$longArtifactName',
contentType:
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
sizeBytes: 123456,
),
],
);
for (final cupertino in <bool>[false, true]) {
await tester.pumpWidget(
artifactListHost(
cupertino: cupertino,
groups: [withLongName],
textScale: 2,
onSelected: (_, _) {},
),
);
expect(tester.takeException(), isNull);
final name = tester.renderObject<RenderBox>(find.text(longArtifactName));
expect(
name.size.height,
greaterThan(120),
reason: 'the recorded name must wrap over several lines, not one',
);
expect(
find.text(
'application/vnd.openxmlformats-officedocument.'
'spreadsheetml.sheet · 120.6${nonBreakingSpace}KiB',
),
findsOneWidget,
);
}
});
testWidgets('a missing name and content type stay explicit', (tester) async {
final group = visitGroup(
artifacts: [
unaddressedArtifact(),
recordedArtifact(
'notes.md',
url: '/artifacts/7/1/notes.md',
contentType: 'text/markdown',
sizeBytes: 812,
),
],
);
await tester.pumpWidget(
artifactListHost(cupertino: false, groups: [group]),
);
expect(find.text('(unnamed artifact)'), findsOneWidget);
expect(
find.text('type not recorded · 0${nonBreakingSpace}B'),
findsOneWidget,
);
expect(find.text('notes.md'), findsOneWidget);
expect(
find.text('text/markdown · 812${nonBreakingSpace}B'),
findsOneWidget,
);
expect(find.byIcon(Icons.check), findsNothing);
});
testWidgets('empty groups keep the honest empty wording', (tester) async {
await tester.pumpWidget(
artifactListHost(cupertino: false, groups: const <ArtifactGroup>[]),
);
expect(find.text('No stage artifacts recorded.'), findsOneWidget);
expect(find.byType(ListTile), findsNothing);
});
}
@@ -0,0 +1,473 @@
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/features/changes/changes.dart';
import 'fixtures.dart';
import 'widget_hosts.dart';
void main() {
testWidgets(
'a missing capture is an evidence gap, not an observed no-change',
(tester) async {
await tester.pumpWidget(
materialHost(ChangesViewer(steps: [stepFixture(fileChanges: null)])),
);
expect(find.text('Changes · not recorded for this run'), findsOneWidget);
expect(find.text('Capture unavailable'), findsOneWidget);
expect(find.text(missingCaptureDetail), findsOneWidget);
expect(find.text(emptyCaptureDetail), findsNothing);
expect(find.text('No changes observed'), findsNothing);
},
);
testWidgets('a running step with no capture is pending, not unavailable', (
tester,
) async {
await tester.pumpWidget(
materialHost(
ChangesViewer(
steps: [stepFixture(status: 'running', fileChanges: null)],
),
),
);
expect(find.text('Changes · capture pending'), findsOneWidget);
expect(find.text('Capture pending'), findsOneWidget);
expect(find.text(pendingCaptureDetail), findsOneWidget);
expect(find.text('Capture unavailable'), findsNothing);
});
testWidgets('a differently cased running status agrees with the header', (
tester,
) async {
await tester.pumpWidget(
materialHost(
ChangesViewer(
steps: [stepFixture(status: 'Running', fileChanges: null)],
),
),
);
expect(find.text('Changes · capture pending'), findsOneWidget);
expect(find.text('Capture pending'), findsOneWidget);
expect(find.text('Capture unavailable'), findsNothing);
});
testWidgets('an empty complete capture says the workspace was unchanged', (
tester,
) async {
await tester.pumpWidget(
materialHost(
ChangesViewer(steps: [stepFixture(fileChanges: captureFixture())]),
),
);
expect(find.text('Changes · no changes observed'), findsOneWidget);
expect(find.text('No changes observed'), findsOneWidget);
expect(find.text(emptyCaptureDetail), findsOneWidget);
expect(find.text(missingCaptureDetail), findsNothing);
});
testWidgets('an unavailable capture never claims there were no changes', (
tester,
) async {
await tester.pumpWidget(
materialHost(
ChangesViewer(
steps: [
stepFixture(
fileChanges: captureFixture(
status: 'unavailable',
diagnostic:
'Workspace snapshot unavailable; changes could not be '
'compared.',
),
),
],
),
),
);
expect(find.text('Changes · capture unavailable'), findsOneWidget);
expect(find.textContaining('Workspace snapshot unavailable'), findsWidgets);
expect(find.text(emptyCaptureDetail), findsNothing);
});
testWidgets('stage/visit sections keep partial status, counters and scope', (
tester,
) async {
final diagnostic = 'Excluded protected files.';
await tester.pumpWidget(
materialHost(
ChangesViewer(
steps: [
stepFixture(
stage: 'implementer',
fileChanges: captureFixture(
status: 'partial',
skipped: 1,
omitted: 2,
diagnostic: diagnostic,
files: [
fileChangeFixture(path: 'lib/a.dart', patch: multiHunkPatch),
],
),
),
stepFixture(
stage: 'reviewer',
sequence: 2,
status: 'failed',
fileChanges: null,
),
],
),
),
);
expect(find.text('implementer'), findsOneWidget);
expect(find.text('Visit 1 · completed'), findsOneWidget);
// The reviewer's first visit is Visit 1, not the run-wide step ordinal 2.
expect(find.text('Visit 1 · failed'), findsOneWidget);
expect(find.text('Visit 2 · failed'), findsNothing);
expect(
find.text(
'partial (1 files), 1 skipped, 2 omitted · Excluded protected files.',
),
findsOneWidget,
);
expect(
find.text('Scope: Git tracked and nonignored files in the run directory'),
findsOneWidget,
);
expect(find.text('reviewer'), findsOneWidget);
expect(find.text(missingCaptureDetail), findsOneWidget);
expect(find.textContaining('partial capture'), findsWidgets);
});
testWidgets(
'repeated stages number their own visits and honour control.visit',
(tester) async {
// Tall enough that the lazy list builds every section.
tester.view.physicalSize = const Size(800, 1400);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
materialHost(
ChangesViewer(
steps: [
stepFixture(
stage: 'implementer',
sequence: 1,
fileChanges: captureFixture(),
),
stepFixture(
stage: 'reviewer',
sequence: 2,
fileChanges: captureFixture(),
),
stepFixture(
stage: 'implementer',
sequence: 3,
fileChanges: captureFixture(),
),
stepFixture(
stage: 'reviewer',
sequence: 4,
visit: 6,
fileChanges: captureFixture(),
),
],
),
),
);
// Both stages' first recorded visits are Visit 1; the run-wide step
// ordinals (1-4) must not leak into the label.
expect(find.text('Visit 1 · completed'), findsNWidgets(2));
expect(find.text('Visit 2 · completed'), findsOneWidget);
// The resumed reviewer visit records control.visit 6.
expect(find.text('Visit 6 · completed'), findsOneWidget);
expect(find.text('Visit 3 · completed'), findsNothing);
expect(find.text('Visit 4 · completed'), findsNothing);
},
);
testWidgets('filtering changed filenames keeps matching rows and says so', (
tester,
) async {
await tester.pumpWidget(
materialHost(
ChangesViewer(
steps: [
stepFixture(
fileChanges: captureFixture(
files: [
fileChangeFixture(path: 'assets/logo.bin', binary: true),
fileChangeFixture(
path: 'lib/feature.dart',
patch: multiHunkPatch,
),
fileChangeFixture(
path: 'docs/notes.md',
kind: 'added',
patch: '@@ -0,0 +1 @@\n+x',
),
],
),
),
],
),
),
);
expect(find.text('assets/logo.bin'), findsOneWidget);
expect(find.text('lib/feature.dart'), findsOneWidget);
await tester.enterText(find.byType(TextField), 'feature');
await tester.pump();
expect(find.text('lib/feature.dart'), findsOneWidget);
expect(find.text('assets/logo.bin'), findsNothing);
expect(find.text('docs/notes.md'), findsNothing);
expect(find.text('1 of 3 changed paths match'), findsOneWidget);
await tester.enterText(find.byType(TextField), 'nothing-here');
await tester.pump();
expect(
find.text('No changed filenames match "nothing-here".'),
findsOneWidget,
);
await tester.enterText(find.byType(TextField), '');
await tester.pump();
expect(find.text('assets/logo.bin'), findsOneWidget);
expect(find.textContaining('changed files match'), findsNothing);
});
testWidgets(
'opening a file shows the rendered patch and copies exact bytes',
(tester) async {
final calls = <MethodCall>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'Clipboard.setData') calls.add(call);
return null;
});
addTearDown(
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, null),
);
await tester.pumpWidget(
materialHost(
ChangesViewer(
steps: [
stepFixture(
fileChanges: captureFixture(
files: [
fileChangeFixture(
path: 'lib/feature.dart',
patch: multiHunkPatch,
),
],
),
),
],
),
),
);
await tester.tap(find.byKey(const ValueKey('change-1-lib/feature.dart')));
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsOneWidget);
expect(find.text('Rendered'), findsOneWidget);
expect(find.text('Raw patch'), findsOneWidget);
final rendered = tester
.widgetList<RichText>(find.byType(RichText))
.map((rich) => rich.text.toPlainText())
.join('\n');
expect(rendered, contains('+ new line'));
expect(rendered, contains('- old line'));
expect(rendered, contains('@@ -20,3 +21,2 @@'));
await tester.tap(find.text('Raw patch'));
await tester.pumpAndSettle();
final raw = tester.widget<Text>(find.text(multiHunkPatch));
expect(raw.data, multiHunkPatch);
expect(raw.softWrap, isFalse);
await tester.tap(find.text('Copy patch'));
await tester.pump();
expect(calls, hasLength(1));
expect(calls.single.arguments, {'text': multiHunkPatch});
expect(find.text('Copied'), findsOneWidget);
await tester.tap(find.byTooltip('Close diff'));
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsNothing);
},
);
testWidgets('binary, truncated and mode-only entries explain the missing diff', (
tester,
) async {
await tester.pumpWidget(
materialHost(
SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 300,
child: FileDiffViewer(
file: FileChange(
path: 'assets/logo.bin',
kind: ChangeKind.modified,
binary: true,
),
),
),
SizedBox(
height: 300,
child: FileDiffViewer(
file: FileChange(
path: 'logs/build.log',
kind: ChangeKind.modified,
patch: '@@ -1 +1 @@\n-a\n+b',
truncated: true,
),
),
),
SizedBox(
height: 300,
child: FileDiffViewer(
file: FileChange(
path: 'scripts/run.sh',
kind: ChangeKind.modified,
beforeMode: '0644',
afterMode: '0755',
),
),
),
],
),
),
),
);
expect(find.text(binaryDiffMessage), findsOneWidget);
expect(find.text(truncatedPatchNote), findsOneWidget);
expect(
find.text(
"Only the file's mode changed (0644→0755); the server recorded no text "
'diff.',
),
findsOneWidget,
);
final copyButtons = <TextButton>[];
for (var index = 0; index < 3; index++) {
final button = find
.ancestor(
of: find.text('Copy patch').at(index),
matching: find.byWidgetPredicate((widget) => widget is TextButton),
)
.first;
copyButtons.add(tester.widget<TextButton>(button));
}
// Binary and mode-only have nothing to copy; the truncated patch still can.
expect(
copyButtons.where((button) => button.onPressed == null),
hasLength(2),
);
expect(
copyButtons.where((button) => button.onPressed != null),
hasLength(1),
);
});
testWidgets(
'Cupertino uses native list tiles, search field and segmented control',
(tester) async {
await tester.pumpWidget(
cupertinoHost(
ChangesViewer(
steps: [
stepFixture(
fileChanges: captureFixture(
files: [
fileChangeFixture(
path: 'lib/feature.dart',
patch: multiHunkPatch,
),
],
),
),
],
),
),
);
expect(find.byType(CupertinoListTile), findsOneWidget);
expect(find.byType(CupertinoSearchTextField), findsOneWidget);
expect(find.byType(TextField), findsNothing);
await tester.tap(find.byKey(const ValueKey('change-1-lib/feature.dart')));
await tester.pumpAndSettle();
expect(
find.byType(CupertinoSlidingSegmentedControl<DiffForm>),
findsOneWidget,
);
expect(find.text('Rendered'), findsOneWidget);
expect(find.text('Raw patch'), findsOneWidget);
await tester.tap(find.byIcon(CupertinoIcons.xmark));
await tester.pumpAndSettle();
expect(
find.byType(CupertinoSlidingSegmentedControl<DiffForm>),
findsNothing,
);
},
);
testWidgets('narrow viewport and large text keep every control reachable', (
tester,
) async {
tester.view.physicalSize = const Size(320, 720);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
materialHost(
ChangesViewer(
steps: [
stepFixture(
fileChanges: captureFixture(
files: [
fileChangeFixture(
path: 'lib/a_rather_long_feature_file_name.dart',
patch: multiHunkPatch,
),
fileChangeFixture(path: 'assets/logo.bin', binary: true),
],
),
),
],
),
scaler: const TextScaler.linear(2),
),
);
expect(tester.takeException(), isNull);
expect(
find.text('lib/a_rather_long_feature_file_name.dart'),
findsOneWidget,
);
// The viewer itself at the same narrow width and 2x text: every action
// stays on screen and the patch body scrolls instead of overflowing.
await tester.pumpWidget(
materialHost(
FileDiffViewer(
file: FileChange(
path: 'lib/a_rather_long_feature_file_name.dart',
kind: ChangeKind.modified,
patch: multiHunkPatch,
),
),
scaler: const TextScaler.linear(2),
),
);
expect(tester.takeException(), isNull);
expect(find.text('Rendered'), findsOneWidget);
expect(find.text('Copy patch'), findsOneWidget);
expect(find.byTooltip('Close diff'), findsOneWidget);
});
}
@@ -0,0 +1,206 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/changes/changes.dart';
import 'package:pipelines_app/features/changes/widgets/change_style.dart';
import 'fixtures.dart';
import 'widget_hosts.dart';
/// The patch has one short context line and one much longer added line, so a
/// text-width tint and a full-hunk-width tint are visibly different sizes.
const _raggedPatch =
'@@ -1,4 +1,4 @@\n'
' short\n'
'+this added line is much longer than every other recorded line here\n'
'-x\n'
' tail\n';
void main() {
test(
'patch typography preserves the native host style without overrides',
() {
const native = TextStyle(fontSize: 19, fontFamily: 'host-font');
expect(nativeDiffText(native), same(native));
},
);
testWidgets(
'light and dark themes give additions and removals distinct hues',
(tester) async {
for (final brightness in [Brightness.light, Brightness.dark]) {
await tester.pumpWidget(
materialHost(const SizedBox.shrink(), brightness: brightness),
);
final context = tester.element(find.byType(Scaffold));
final add = diffLineColors(context, ChangeLineKind.add);
final remove = diffLineColors(context, ChangeLineKind.remove);
expect(add.background, isNull);
expect(remove.background, isNull);
expect(add.text, isNot(remove.text), reason: '$brightness text');
expect(add.text, Theme.of(context).colorScheme.primary);
expect(remove.text, Theme.of(context).colorScheme.error);
}
},
);
testWidgets('every diff line shares the hunk width, not its own text width', (
tester,
) async {
await tester.pumpWidget(
materialHost(
SizedBox(
height: 400,
child: FileDiffViewer(
file: FileChange(
path: 'lib/ragged.dart',
kind: ChangeKind.modified,
patch: _raggedPatch,
),
),
),
),
);
await tester.pumpAndSettle();
final widths = [
for (var index = 0; index < 4; index++)
tester.getSize(find.byKey(ValueKey('diff-line-$index'))).width,
];
for (final width in widths) {
expect(width, closeTo(widths.first, 0.01));
}
// The widest recorded line sets the hunk width, well beyond a short line.
expect(widths.first, greaterThan(300));
});
testWidgets('the stat line colours additions and removals apart', (
tester,
) async {
await tester.pumpWidget(
materialHost(
SizedBox(
height: 400,
child: FileDiffViewer(
file: FileChange(
path: 'lib/feature.dart',
kind: ChangeKind.modified,
patch: multiHunkPatch,
),
),
),
),
);
await tester.pumpAndSettle();
final stat = tester.widgetList<RichText>(find.byType(RichText)).firstWhere((
rich,
) {
final span = rich.text;
return span is TextSpan &&
span.children != null &&
span.toPlainText() == '+2 -2';
});
final root = (stat.text as TextSpan).children!.single as TextSpan;
final spans = root.children!.cast<TextSpan>();
final added = spans.firstWhere((span) => span.text == '+2');
final removed = spans.firstWhere((span) => span.text == '-2');
expect(added.style!.color, isNot(removed.style!.color));
});
testWidgets('the raw view scrolls long lines instead of wrapping them', (
tester,
) async {
await tester.pumpWidget(
materialHost(
SizedBox(
height: 400,
child: FileDiffViewer(
file: FileChange(
path: 'lib/feature.dart',
kind: ChangeKind.modified,
patch: multiHunkPatch,
),
),
),
),
);
await tester.tap(find.text('Raw patch'));
await tester.pumpAndSettle();
expect(find.text(multiHunkPatch), findsOneWidget);
expect(
find.ancestor(
of: find.text(multiHunkPatch),
matching: find.byWidgetPredicate(
(widget) =>
widget is SingleChildScrollView &&
widget.scrollDirection == Axis.horizontal,
),
),
findsOneWidget,
);
});
testWidgets('a Cupertino row wraps its recorded path instead of clipping it', (
tester,
) async {
tester.view.physicalSize = const Size(320, 720);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
const path =
'lib/features/changes/domain/a_rather_long_unified_patch_file_name.dart';
await tester.pumpWidget(
cupertinoHost(
ChangesViewer(
steps: [
stepFixture(
fileChanges: captureFixture(
files: [fileChangeFixture(path: path, patch: multiHunkPatch)],
),
),
],
),
),
);
final rich = tester
.widgetList<RichText>(find.byType(RichText))
.firstWhere((widget) => widget.text.toPlainText() == path);
// CupertinoListTile caps a title at one ellipsized line; the row must lift
// that cap so the filename stays visible.
expect(rich.maxLines, isNull);
expect(rich.overflow, TextOverflow.visible);
expect(tester.getSize(find.text(path)).height, greaterThan(30));
expect(tester.takeException(), isNull);
});
testWidgets('a Cupertino phone dialog is inset from the screen edge', (
tester,
) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
cupertinoHost(
ChangesViewer(
steps: [
stepFixture(
fileChanges: captureFixture(
files: [
fileChangeFixture(
path: 'lib/feature.dart',
patch: multiHunkPatch,
),
],
),
),
],
),
),
);
await tester.tap(find.byKey(const ValueKey('change-1-lib/feature.dart')));
await tester.pumpAndSettle();
final rect = tester.getRect(find.byType(CupertinoPopupSurface));
expect(rect.width, lessThanOrEqualTo(390 - 24));
expect(rect.left, greaterThan(8));
expect(rect.right, lessThan(382));
expect(tester.takeException(), isNull);
});
}
+67
View File
@@ -0,0 +1,67 @@
import 'package:pipelines_app/core/api_gateway.dart';
/// Server-shaped fixtures shared by the Changes tests. These mirror the JSON
/// `internal/protocol.StageFileChanges` / `FileChange` writer, including quoted
/// unified headers and optional fields.
const multiHunkPatch =
'--- "a/lib/feature.dart"\n'
'+++ "b/lib/feature.dart"\n'
'@@ -1,4 +1,5 @@\n'
' context one\n'
'-old line\n'
'+new line\n'
'+added line\n'
' context two\n'
' context three\n'
'@@ -20,3 +21,2 @@\n'
' context twenty\n'
'-removed line\n'
' context twenty-two\n';
JsonMap fileChangeFixture({
required String path,
String kind = 'modified',
String patch = '',
bool binary = false,
bool truncated = false,
String? beforeMode,
String? afterMode,
}) => {
'path': path,
'kind': kind,
'patch': patch,
if (binary) 'binary': true,
if (truncated) 'truncated': true,
'before_mode': ?beforeMode,
'after_mode': ?afterMode,
};
JsonMap captureFixture({
String status = 'complete',
List<JsonMap> files = const [],
int skipped = 0,
int omitted = 0,
String diagnostic = '',
String scope = 'Git tracked and nonignored files in the run directory',
}) => {
'status': status,
'scope': scope,
'files': files,
'skipped': skipped,
'omitted': omitted,
'diagnostic': diagnostic,
};
JsonMap stepFixture({
String stage = 'implementer',
int sequence = 1,
String status = 'completed',
JsonMap? fileChanges,
int? visit,
}) => {
'stage': stage,
'sequence': sequence,
'status': status,
'file_changes': fileChanges,
if (visit != null) 'control': {'visit': visit},
};
@@ -0,0 +1,624 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/changes/domain/change_capture.dart';
import 'package:pipelines_app/features/changes/domain/change_kind.dart';
import 'package:pipelines_app/features/changes/domain/change_wording.dart';
import 'package:pipelines_app/features/changes/domain/file_change.dart';
import 'package:pipelines_app/features/changes/domain/run_changes.dart';
import 'fixtures.dart';
// Thin map-override wrappers over the shared server-shaped fixtures; the
// canonical field shapes live in fixtures.dart.
JsonMap file(JsonMap overrides) => {
...fileChangeFixture(path: 'a.txt'),
...overrides,
};
JsonMap step(JsonMap overrides) => {...stepFixture(stage: 's'), ...overrides};
JsonMap capture({
String status = 'complete',
List<JsonMap> files = const [],
int skipped = 0,
int omitted = 0,
String diagnostic = '',
String scope = 'Git tracked and nonignored files in the run directory',
}) => captureFixture(
status: status,
files: files,
skipped: skipped,
omitted: omitted,
diagnostic: diagnostic,
scope: scope,
);
void main() {
test(
'a null capture is pending while running/waiting, otherwise missing',
() {
final running = runChanges([
step({'status': 'running'}),
step({'status': 'waiting'}),
]);
expect(running.pending, isTrue);
expect(running.missingCaptures, 0);
expect(running.stepsWithChanges, 0);
final missing = runChanges([
step({'status': 'completed'}),
step({'status': 'failed'}),
]);
expect(missing.pending, isFalse);
expect(missing.missingCaptures, 2);
expect(missing.stepsWithChanges, 0);
},
);
test('a non-null malformed capture is unavailable, not a no-change', () {
final changes = runChanges([
step({'file_changes': 'not-an-object'}),
]);
expect(changes.stepsWithChanges, 1);
expect(changes.missingCaptures, 0);
expect(changes.unavailable, isTrue);
expect(changes.files, isEmpty);
expect(runChangesHeader(changes), 'Changes · capture unavailable');
expect(runChangesNote(changes), malformedCaptureDetail);
});
test('a present capture with no files is a captured no-change', () {
final changes = runChanges([
step({'stage': 'a', 'file_changes': capture()}),
]);
expect(changes.stepsWithChanges, 1);
expect(changes.files, isEmpty);
expect(changes.partial, isFalse);
expect(runChangesHeader(changes), 'Changes · no changes observed');
expect(noChangeDetail(changes), emptyCaptureDetail);
});
test('a later visit wins the kind, including an unrecognised later kind', () {
final changes = runChanges([
step({
'stage': 'a',
'file_changes': capture(
files: [
file({'path': 'x', 'kind': 'modified'}),
],
),
}),
step({
'stage': 'b',
'file_changes': capture(
files: [
file({'path': 'x', 'kind': 'added'}),
],
),
}),
]);
expect(changes.files.single.kind, ChangeKind.added);
expect(changes.files.single.steps, ['a', 'b']);
final unknown = runChanges([
step({
'stage': 'a',
'file_changes': capture(
files: [
file({'path': 'x', 'kind': 'added'}),
],
),
}),
step({
'stage': 'b',
'file_changes': capture(
files: [
file({'path': 'x', 'kind': 'copied'}),
],
),
}),
]);
expect(unknown.files.single.kind, ChangeKind.other);
});
test('three visits report only the last visit facts', () {
final changes = runChanges([
step({
'stage': 'a',
'sequence': 1,
'file_changes': capture(
files: [
file({
'path': 'x',
'kind': 'modified',
'patch': '@@ -1 +1 @@\n-old\n+one',
'before_mode': '0644',
'after_mode': '0644',
}),
],
),
}),
step({
'stage': 'b',
'sequence': 2,
'file_changes': capture(
files: [
file({
'path': 'x',
'patch': '@@ -1 +1 @@\n-one\n+two',
'before_mode': '0644',
'after_mode': '0644',
}),
],
),
}),
step({
'stage': 'c',
'sequence': 3,
'file_changes': capture(
files: [
file({
'path': 'x',
'kind': 'added',
'patch': '@@ -1 +2 @@\n-two\n+three\n+four',
'before_mode': '0755',
'after_mode': '0600',
}),
],
),
}),
]);
final entry = changes.files.single;
expect(entry.kind, ChangeKind.added);
expect(entry.added, 2);
expect(entry.removed, 1);
expect(entry.patch, '@@ -1 +2 @@\n-two\n+three\n+four');
expect(entry.beforeMode, '0755');
expect(entry.afterMode, '0600');
expect(entry.modeChanged, isTrue);
expect(entry.steps, ['a', 'b', 'c']);
expect(changeRowMeta(entry), 'changed by a → b → c · mode 0755→0600');
expect(changes.added, 2);
expect(changes.removed, 1);
});
test('later binary/truncated flags replace earlier rows', () {
final changes = runChanges([
step({
'stage': 'a',
'file_changes': capture(
files: [
file({
'path': 'x',
'patch': '@@ -1 +1 @@\n-old\n+new',
'binary': true,
'truncated': true,
'before_mode': '0644',
'after_mode': '0755',
}),
],
),
}),
step({
'stage': 'b',
'file_changes': capture(
files: [
file({
'path': 'x',
'patch': '',
'binary': false,
'truncated': false,
'before_mode': '0755',
'after_mode': '0755',
}),
],
),
}),
]);
final entry = changes.files.single;
expect(entry.binary, isFalse);
expect(entry.truncated, isFalse);
expect(entry.patch, isNull);
expect(entry.modeChanged, isFalse);
expect(entry.added, 0);
expect(entry.removed, 0);
// A truncated row anywhere in the run still makes the capture partial.
expect(changes.partial, isTrue);
});
test('paths keep first-seen order while ordering follows sequence', () {
final changes = runChanges([
step({
'stage': 'c',
'sequence': 3,
'file_changes': capture(
files: [
file({'path': 'y'}),
],
),
}),
step({
'stage': 'a',
'sequence': 1,
'file_changes': capture(
files: [
file({'path': 'y'}),
],
),
}),
step({
'stage': 'b',
'sequence': 2,
'file_changes': capture(
files: [
file({'path': 'x'}),
],
),
}),
]);
expect(changes.files.map((entry) => entry.path), ['y', 'x']);
expect(changes.files.first.kind, ChangeKind.modified);
expect(changes.files.first.steps, ['a', 'c']);
expect(changeRowMeta(changes.files.first), 'changed by a → c');
});
test(
'stage names are deduped in run order; blank names/paths are handled',
() {
final changes = runChanges([
step({
'stage': 'implementer',
'file_changes': capture(
files: [
file({'path': 'x'}),
],
),
}),
step({
'stage': 'reviewer',
'file_changes': capture(
files: [
file({'path': 'x'}),
],
),
}),
step({
'stage': 'implementer',
'file_changes': capture(
files: [
file({'path': 'x'}),
file({'path': ' '}),
],
),
}),
]);
expect(changes.files.single.steps, ['implementer', 'reviewer']);
final blank = runChanges([
step({
'stage': ' ',
'file_changes': capture(
files: [
file({'path': 'x'}),
],
),
}),
]);
expect(blank.files.single.steps, ['stage']);
},
);
test('partial is OR-ed from status, a truncated file or omitted count', () {
expect(
runChanges([
step({'file_changes': capture(status: 'partial')}),
]).partial,
isTrue,
);
expect(
runChanges([
step({
'file_changes': capture(
files: [
file({'truncated': true}),
],
),
}),
]).partial,
isTrue,
);
expect(
runChanges([
step({'file_changes': capture(omitted: 2)}),
]).partial,
isTrue,
);
});
test('diagnostics from several captures are deduped and joined', () {
final changes = runChanges([
step({'file_changes': capture(status: 'partial', diagnostic: 'why one')}),
step({'file_changes': capture(status: 'partial', diagnostic: 'why one')}),
step({'file_changes': capture(status: 'partial', diagnostic: 'why two')}),
]);
expect(changes.diagnostic, 'why one why two');
expect(changes.stepsWithChanges, 3);
});
test(
'stageCaptures keeps every visit, including a missing one, in order',
() {
final visits = stageCaptures([
step({'stage': 'reviewer', 'sequence': 2, 'file_changes': capture()}),
step({'stage': 'implementer', 'sequence': 1, 'file_changes': null}),
]);
expect(visits.map((visit) => visit.stage), ['implementer', 'reviewer']);
expect(visits.first.missing, isTrue);
expect(visits.last.capture?.status, 'complete');
},
);
test(
'visit is control.visit when positive, else the position in its stage',
() {
final visits = stageCaptures([
stepFixture(stage: 'implementer', sequence: 1),
stepFixture(stage: 'reviewer', sequence: 2),
stepFixture(stage: 'implementer', sequence: 3),
stepFixture(stage: 'implementer', sequence: 4, visit: 7),
stepFixture(stage: 'reviewer', sequence: 5, visit: 0),
]);
expect(visits.map((visit) => '${visit.stage}:${visit.visit}'), [
'implementer:1',
'reviewer:1',
'implementer:2',
'implementer:7',
'reviewer:2',
]);
},
);
test('equal sequences keep their input order for stage positions', () {
final visits = stageCaptures([
stepFixture(stage: 's', sequence: 1),
stepFixture(stage: 's', sequence: 1),
stepFixture(stage: 'other', sequence: 0),
]);
expect(visits.map((visit) => '${visit.stage}:${visit.visit}'), [
'other:1',
's:1',
's:2',
]);
});
test('capture parsing keeps scope, counters and diagnostic', () {
final parsed = ChangeCapture.fromJson(
capture(
status: 'partial',
skipped: 2,
omitted: 1,
diagnostic: 'Excluded protected files.',
files: [
file({'path': 'x'}),
file({'path': ''}),
],
),
);
expect(parsed.scope, contains('Git tracked'));
expect(parsed.skipped, 2);
expect(parsed.omitted, 1);
expect(parsed.diagnostic, 'Excluded protected files.');
expect(parsed.files.map((entry) => entry.path), ['x']);
expect(
fileChangesSummary(parsed),
'partial (1 files), 2 skipped, 1 omitted · Excluded protected files.',
);
});
test('header covers every empty-capture variant', () {
expect(
runChangesHeader(_run(unavailable: true, files: const [])),
'Changes · capture unavailable',
);
expect(runChangesHeader(_run(pending: true)), 'Changes · capture pending');
expect(
runChangesHeader(_run(partial: true, stepsWithChanges: 1)),
'Changes · partial capture',
);
expect(runChangesHeader(_run()), 'Changes · not recorded for this run');
expect(
runChangesHeader(_run(stepsWithChanges: 1, missingCaptures: 1)),
'Changes · capture incomplete',
);
expect(
runChangesHeader(_run(stepsWithChanges: 2)),
'Changes · no changes observed',
);
});
test('note spells partial, missing and unavailable wording', () {
expect(
runChangesNote(_run(unavailable: true)),
'The workspace snapshot could not be compared; the changes below may be '
'incomplete.',
);
expect(
runChangesNote(_run(unavailable: true, diagnostic: 'server says so')),
'server says so',
);
expect(
runChangesNote(
_run(
partial: true,
skipped: 8,
diagnostic: 'Excluded protected files.',
missingCaptures: 1,
),
),
'Partial capture: some changes may be missing. (8 files skipped) '
'Excluded protected files. Missing capture: 1 stage did not record '
'changes.',
);
expect(
runChangesNote(
_run(
partial: true,
omitted: 3,
missingCaptures: 2,
files: [
FileChange(path: 'x', kind: ChangeKind.modified, truncated: true),
FileChange(path: 'y', kind: ChangeKind.modified, truncated: true),
],
),
),
'Partial capture: some changes may be missing. (3 omitted, 2 truncated) '
'Missing capture: 2 stages did not record changes.',
);
expect(runChangesNote(_run()), '');
});
test('tags, row meta and unavailable reasons are exact', () {
final binary = FileChange(
path: 'x',
kind: ChangeKind.modified,
binary: true,
truncated: false,
beforeMode: '0644',
afterMode: '0755',
steps: const ['a'],
);
expect(changeEntryTags(binary), ['binary']);
expect(changeRowMeta(binary), 'changed by a · binary');
final truncated = FileChange(
path: 'x',
kind: ChangeKind.modified,
truncated: true,
steps: const ['a', 'b'],
);
expect(changeEntryTags(truncated), ['truncated']);
expect(changeRowMeta(truncated), 'changed by a → b · truncated');
final modeOnly = FileChange(
path: 'x',
kind: ChangeKind.modified,
beforeMode: '0644',
afterMode: '0755',
steps: const ['a'],
);
expect(changeEntryTags(modeOnly), ['mode change']);
expect(
changeRowMeta(modeOnly),
'changed by a · mode change · mode 0644→0755',
);
expect(
patchUnavailableReason(modeOnly),
"Only the file's mode changed (0644→0755); the server recorded no text "
'diff.',
);
expect(
patchUnavailableReason(truncated),
"The server truncated this file's patch at its capture limit; no diff "
'text was recorded.',
);
expect(
patchUnavailableReason(FileChange(path: 'x', kind: ChangeKind.modified)),
'The server recorded this change without a patch.',
);
});
test('changed filenames filter is case-insensitive and preserves order', () {
final files = [
FileChange(path: 'lib/Changes_Viewer.dart', kind: ChangeKind.modified),
FileChange(path: 'docs/notes.md', kind: ChangeKind.added),
FileChange(path: 'lib/file_diff_viewer.dart', kind: ChangeKind.added),
];
expect(filterFileChanges(files, 'VIEWER').map((file) => file.path), [
'lib/Changes_Viewer.dart',
'lib/file_diff_viewer.dart',
]);
expect(filterFileChanges(files, ' '), files);
expect(filterFileChanges(files, 'absent'), isEmpty);
});
test('a real-shaped partial run aggregates once and keeps the gap visible', () {
const diagnostic =
'Excluded protected, symlinked, oversized or unreadable files; this is '
'not a complete workspace diff.';
final changes = runChanges([
step({
'stage': 'implementer',
'sequence': 1,
'file_changes': capture(
status: 'partial',
skipped: 2,
diagnostic: diagnostic,
files: [
file({
'path': 'docs/notes.md',
'kind': 'added',
'patch': '@@ -0,0 +1 @@\n+notes',
}),
file({
'path': 'internal/server/retry_test.go',
'patch': '@@ -1 +1 @@\n-old\n+new',
}),
],
),
}),
step({
'stage': 'reviewer',
'sequence': 2,
'file_changes': capture(
status: 'partial',
skipped: 2,
diagnostic: diagnostic,
),
}),
step({'stage': 'ui_reviewer', 'sequence': 3}),
]);
expect(changes.files, hasLength(2));
expect(changes.stepsWithChanges, 2);
expect(changes.missingCaptures, 1);
expect(changes.partial, isTrue);
expect(changes.skipped, 4);
expect(
runChangesHeader(changes),
'2 files changed · +2 -1 · partial capture',
);
expect(
runChangesNote(changes),
'Partial capture: some changes may be missing. (4 files skipped) '
'$diagnostic Missing capture: 1 stage did not record changes.',
);
expect(
runChangesHeader(_run(unavailable: true, files: changes.files)),
'Changes · capture unavailable',
);
});
}
RunChanges _run({
List<FileChange> files = const [],
bool partial = false,
bool unavailable = false,
bool pending = false,
int stepsWithChanges = 0,
int missingCaptures = 0,
int skipped = 0,
int omitted = 0,
String diagnostic = '',
}) => RunChanges(
files: files,
stepsWithChanges: stepsWithChanges,
stepsPending: 0,
added: files.fold(0, (sum, file) => sum + file.added),
removed: files.fold(0, (sum, file) => sum + file.removed),
partial: partial,
unavailable: unavailable,
pending: pending,
missingCaptures: missingCaptures,
skipped: skipped,
omitted: omitted,
diagnostic: diagnostic,
);
@@ -0,0 +1,176 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/changes/domain/unified_patch.dart';
void main() {
test('a blank or absent patch parses to an empty result', () {
for (final blank in <dynamic>['', ' ', '\n', null]) {
final parsed = parseUnifiedPatch(blank);
expect(parsed.raw, '');
expect(parsed.headerLines, isEmpty);
expect(parsed.hunks, isEmpty);
expect(parsed.added, 0);
expect(parsed.removed, 0);
}
});
test('a single hunk is numbered and counted', () {
final patch = [
'--- "a/x.txt"',
'+++ "b/x.txt"',
'@@ -1,3 +1,3 @@',
' ctx',
'-old',
'+new',
' tail',
].join('\n');
final parsed = parseUnifiedPatch(patch);
expect(parsed.raw, patch);
expect(parsed.headerLines, ['--- "a/x.txt"', '+++ "b/x.txt"']);
expect(parsed.hunks, hasLength(1));
final hunk = parsed.hunks.single;
expect(hunk.header, '@@ -1,3 +1,3 @@');
expect(
[hunk.oldStart, hunk.oldCount, hunk.newStart, hunk.newCount],
[1, 3, 1, 3],
);
expect(
[
for (final line in hunk.lines)
[line.kind, line.text, line.oldLine, line.newLine],
],
[
[ChangeLineKind.context, 'ctx', 1, 1],
[ChangeLineKind.remove, 'old', 2, 0],
[ChangeLineKind.add, 'new', 0, 2],
[ChangeLineKind.context, 'tail', 3, 3],
],
);
expect(parsed.added, 1);
expect(parsed.removed, 1);
});
test('a missing count defaults to 1', () {
final hunk = parseUnifiedPatch('@@ -5 +7 @@\n-old\n+new').hunks.single;
expect(
[hunk.oldStart, hunk.oldCount, hunk.newStart, hunk.newCount],
[5, 1, 7, 1],
);
});
test('a multi-hunk patch keeps each hunk header and its own numbering', () {
final parsed = parseUnifiedPatch(
[
'--- "a/lib/x.dart"',
'+++ "b/lib/x.dart"',
'@@ -1,2 +1,3 @@',
' one',
'+two',
' three',
'@@ -40,3 +41,2 @@',
' forty',
'-forty-one',
' forty-two',
].join('\n'),
);
expect(parsed.hunks, hasLength(2));
expect(parsed.hunks[0].lines.map((line) => line.newLine), [1, 2, 3]);
expect(parsed.hunks[1].lines.map((line) => line.oldLine), [40, 41, 42]);
expect(parsed.added, 1);
expect(parsed.removed, 1);
expect(parsed.headerLines, ['--- "a/lib/x.dart"', '+++ "b/lib/x.dart"']);
});
test('a no-newline marker is shown verbatim and never numbered', () {
final lines = parseUnifiedPatch(
[
'@@ -1 +1 @@',
'-one',
r'\ No newline at end of file',
'+two',
].join('\n'),
).hunks.single.lines;
expect(lines[1].noNewlineMarker, isTrue);
expect(lines[1].text, r'\ No newline at end of file');
expect(lines[1].oldLine, 0);
expect(lines[1].newLine, 0);
expect(lines[1].kind, ChangeLineKind.context);
});
test('a second file header closes the current hunk', () {
final parsed = parseUnifiedPatch(
[
'--- "a/x"',
'+++ "b/x"',
'@@ -1 +1 @@',
'-old',
'+new',
'--- "a/y"',
'+++ "b/y"',
'@@ -1 +1 @@',
'-alt',
'+neu',
].join('\n'),
);
expect(parsed.hunks, hasLength(2));
expect(parsed.hunks[0].lines.map((line) => line.text), ['old', 'new']);
expect(parsed.hunks[1].lines.map((line) => line.text), ['alt', 'neu']);
expect(
parsed.headerLines.where((line) => line.startsWith('--- ')),
hasLength(2),
);
expect(parsed.added, 2);
expect(parsed.removed, 2);
});
test('metadata before a hunk is kept; a truncated tail is unnumbered', () {
final parsed = parseUnifiedPatch(
[
'index abc..def 100644',
'--- "a/x"',
'+++ "b/x"',
'@@ -1 +1 @@',
'-old',
'+new',
'trailing trunc',
].join('\n'),
);
expect(parsed.headerLines.first, 'index abc..def 100644');
final tail = parsed.hunks.single.lines.last;
expect(tail.kind, ChangeLineKind.context);
expect(tail.text, 'trailing trunc');
expect([tail.oldLine, tail.newLine], [0, 0]);
});
test('a trailing newline becomes a numbered empty context line', () {
final lines = parseUnifiedPatch('@@ -1 +1 @@\n ctx\n').hunks.single.lines;
expect(lines, hasLength(2));
expect([lines[1].text, lines[1].oldLine, lines[1].newLine], ['', 2, 2]);
});
test('gutter width, gutter text, symbols and stat match the web wording', () {
expect(
gutterWidth(
const PatchHunk(
header: 'h',
oldStart: 0,
oldCount: 0,
newStart: 0,
newCount: 0,
lines: [],
),
),
1,
);
final hunk = parseUnifiedPatch('@@ -9,1 +12,1 @@\n-a\n+b').hunks.single;
expect(gutterWidth(hunk), 2);
expect(gutterText(0, 2), ' ');
expect(gutterText(7, 2), ' 7');
expect(diffLineSymbol(ChangeLineKind.add), '+');
expect(diffLineSymbol(ChangeLineKind.remove), '-');
expect(diffLineSymbol(ChangeLineKind.context), ' ');
expect(changeStat(3, 2), '+3 -2');
expect(changeStat(3, 0), '+3');
expect(changeStat(0, 2), '-2');
expect(changeStat(0, 0), '');
});
}
@@ -0,0 +1,41 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// The two platform hosts the Changes widget tests share: Material for
/// Android/desktop/web and Cupertino for iOS/macOS. They state the platform
/// explicitly instead of mutating a global debug override.
Widget materialHost(
Widget child, {
TextScaler scaler = TextScaler.noScaling,
Brightness brightness = Brightness.light,
}) {
return MaterialApp(
theme: ThemeData(brightness: brightness),
builder: (context, app) => MediaQuery(
data: MediaQuery.of(context).copyWith(textScaler: scaler),
child: app!,
),
home: Scaffold(body: child),
);
}
Widget cupertinoHost(
Widget child, {
TextScaler scaler = TextScaler.noScaling,
Brightness brightness = Brightness.light,
}) {
return CupertinoApp(
theme: CupertinoThemeData(brightness: brightness),
builder: (context, app) => Theme(
// The real app selects Cupertino by platform; the test host states it
// explicitly without changing a global debug override. The Theme wraps
// the Navigator so dialogs opened later resolve the same platform.
data: ThemeData(platform: TargetPlatform.iOS),
child: MediaQuery(
data: MediaQuery.of(context).copyWith(textScaler: scaler),
child: app!,
),
),
home: CupertinoPageScaffold(child: SafeArea(child: child)),
);
}
@@ -0,0 +1,316 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/data/chat_repository.dart';
import 'package:pipelines_app/features/chat/domain/chat_sessions.dart';
import 'package:pipelines_app/features/chat/domain/chat_transcript.dart';
class RecordingGateway implements ApiGateway {
final calls = <({String type, JsonMap fields})>[];
JsonMap reply = {};
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add((type: type, fields: fields));
return reply;
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
void main() {
group('chat domain', () {
test(
'filters/groups in server order and keeps server usage unknowns unavailable',
() {
final sessions = [
{'id': 'a', 'directory': '/work', 'title': 'First'},
{'id': 'b', 'directory': '/else', 'title': 'Second'},
{'id': 'c', 'directory': '/work', 'title': 'Third'},
];
expect(filterChatSessions(sessions, 'ELSE').single['id'], 'b');
expect(groupChatSessions(sessions).map((g) => g.directory), [
'/work',
'/else',
]);
expect(chatSessionActivity(running: true, unseen: true), 'streaming');
expect(
chatUsageSnapshot({
'total_tokens': 3,
'context_window': 'unknown',
})!['context_window'],
isNull,
);
expect(chatUsageSnapshot({'legacy_tokens': 9}), isNull);
},
);
test(
'merges pages by id, retains idless events, replaces authority, and folds parts',
() {
final first = mergeChatHistory({}, {
'messages': [
{
'id': 'a',
'role': 'assistant',
'parts': [
{'type': 'reasoning', 'text': 'think'},
],
},
{
'role': 'assistant',
'parts': [
{'type': 'future_part', 'payload': 4},
],
},
{'id': 'u', 'role': 'user', 'text': 'hello', 'operation_id': 'op'},
],
'nextCursor': 'opaque/1',
'hasMore': true,
});
final older = mergeChatHistory(first, {
'messages': [
{
'id': 'a',
'role': 'assistant',
'parts': [
{'type': 'text', 'text': 'final'},
],
},
],
'nextCursor': '',
'hasMore': false,
}, older: true);
expect(older['nextCursor'], '');
final msgs = older['messages'] as List<JsonMap>;
expect(msgs.map((m) => m['id']), ['a', null, 'u']);
expect(
(transcriptRows(msgs).first['parts'] as List).map((p) => p['type']),
['text', 'future_part'],
);
expect(
reconcileChatUser(msgs, {
'id': 'remote',
'role': 'user',
'operation_id': 'op',
}).where((m) => m['operation_id'] == 'op').length,
1,
);
},
);
test(
'send queue is session-scoped and operation IDs deduplicate retries',
() {
final queue = ChatSendQueue();
final send = QueuedChatSend(
operationId: 'stable',
text: ' prompt ',
files: ['/tmp/a'],
);
expect(queue.enqueue('s1', send), isTrue);
expect(queue.enqueue('s1', send.retry()), isFalse);
expect(queue.enqueue('s2', send.retry()), isTrue);
expect(queue.takeNext('s1')!.operationId, 'stable');
expect(queue.takeNext('s1'), isNull);
expect(queue.forSession('s2').single.files, ['/tmp/a']);
},
);
test(
'live text/reasoning append, tool snapshots merge, and steps settle only activity',
() {
var thread = <String, dynamic>{
'sessionId': 's',
'messages': <JsonMap>[],
};
thread = applyChatEvent(thread, {
'kind': 'text',
'session_id': 's',
'message_id': 'a',
'part': {'id': 'p'},
'delta': 'one',
});
thread = applyChatEvent(thread, {
'kind': 'text',
'session_id': 's',
'message_id': 'a',
'part': {'id': 'p'},
'delta': ' two',
});
thread = applyChatEvent(thread, {
'kind': 'reasoning',
'session_id': 's',
'message_id': 'a',
'part': {'id': 'r'},
'delta': 'hidden',
});
thread = applyChatEvent(thread, {
'kind': 'tool',
'session_id': 's',
'message_id': 'a',
'part': {
'id': 't',
'type': 'tool',
'state': {'input': 'x'},
},
});
thread = applyChatEvent(thread, {
'kind': 'tool',
'session_id': 's',
'message_id': 'a',
'part': {
'id': 't',
'type': 'tool',
'state': {'status': 'completed'},
},
});
final parts =
((thread['messages'] as List).single as JsonMap)['parts']
as List<JsonMap>;
expect(parts[0]['text'], 'one two');
expect(parts[1]['text'], 'hidden');
expect(parts[2]['state'], {'input': 'x', 'status': 'completed'});
expect(thread['running'], true);
thread = applyChatEvent(thread, {
'kind': 'step',
'session_id': 's',
'step': {'status': 'ended', 'turn_id': 'turn'},
});
expect(thread['running'], false);
expect(
applyChatEvent(thread, {'kind': 'text', 'session_id': 'other'}),
same(thread),
);
},
);
});
group('chat wire adapter', () {
late RecordingGateway gateway;
late ChatRepository repo;
setUp(() {
gateway = RecordingGateway();
repo = ChatRepository(gateway);
});
test('uses web envelopes and opaque history cursor', () async {
gateway.reply = {
'chat_history': {
'messages': [
{'id': 'm', 'role': 'user'},
],
'next_cursor': 'opaque',
'has_more': true,
},
};
final page = await repo.history('s', cursor: 'before', limit: 17);
expect(page['nextCursor'], 'opaque');
expect(gateway.calls.last.type, 'chat_messages');
expect(gateway.calls.last.fields, {
'chat_query': {'session_id': 's', 'cursor': 'before', 'limit': 17},
});
await repo.subscribe('s');
expect(gateway.calls.last.fields, {
'chat_subscribe': {'session_id': 's'},
});
});
test(
'sends stable operation id, omits empty files, and builds action envelopes',
() async {
await repo.prompt('s', ' hi ', operationId: 'same');
expect(gateway.calls.last.fields, {
'chat_prompt': {
'session_id': 's',
'text': 'hi',
'operation_id': 'same',
'native_message_id': 'msg_same',
},
});
await repo.answerForm('s', 'f', {'choice': 'yes'}, action: 'submit');
expect(gateway.calls.last.fields, {
'chat_answer': {
'session_id': 's',
'form_id': 'f',
'answers': {'choice': 'yes'},
'action': 'submit',
},
});
await repo.replyPermission('s', 'r', 'once', message: ' approved ');
expect(gateway.calls.last.fields, {
'chat_reply': {
'session_id': 's',
'request_id': 'r',
'decision': 'once',
'client': 'Web',
'message': 'approved',
},
});
await repo.create(title: 'New', directory: '~', operationId: 'create');
expect(gateway.calls.last.fields, {
'chat_create': {
'title': 'New',
'directory': '~',
'operation_id': 'create',
},
});
await repo.selectModel('s', 'provider', 'model');
expect(gateway.calls.last.type, 'chat_model');
},
);
test('rejects invalid permissions and prompts before sending', () async {
expect(
() => repo.prompt(' ', 'hello', operationId: 'x'),
throwsArgumentError,
);
expect(
() => repo.prompt('s', ' ', operationId: 'x'),
throwsArgumentError,
);
expect(
() => repo.replyPermission('s', 'r', 'approve'),
throwsArgumentError,
);
expect(gateway.calls, isEmpty);
});
test(
'uses the server model catalog object and default history limit',
() async {
gateway.reply = {
'chat_models': {
'providers': {
'p': ['m'],
},
},
};
expect((await repo.models('s'))['providers'], {
'p': ['m'],
});
expect(gateway.calls.single.fields, {
'chat_query': {'session_id': 's'},
});
gateway.calls.clear();
await repo.history('s');
expect(gateway.calls.single.fields['chat_query']['limit'], 200);
},
);
test(
'reads exact directory/backend catalog envelopes without inventing fallback',
() async {
gateway.reply = {
'chat_directories': ['~', '/work'],
};
expect(await repo.directories(), ['~', '/work']);
expect(gateway.calls.last.type, 'chat_directories');
expect(gateway.calls.last.fields, isEmpty);
gateway.reply = {
'chat_backends': ['opencode', 'claude'],
};
expect(await repo.backends(), ['opencode', 'claude']);
expect(gateway.calls.last.type, 'chat_backends');
expect(gateway.calls.last.fields, isEmpty);
gateway.reply = {};
await expectLater(repo.directories(), throwsStateError);
await expectLater(repo.backends(), throwsStateError);
},
);
});
}
@@ -0,0 +1,217 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
void main() {
testWidgets(
'material create dialog retains the draft through a delayed catalog failure and retry',
(tester) async {
final gateway = FakeChatGateway();
final directories = Completer<JsonMap>();
gateway.directoriesHandler = () => directories.future;
JsonMap? opened;
await pumpMaterialChat(
tester,
gateway,
onOpen: (session) => opened = session,
);
await tester.tap(find.byKey(const Key('chat-new-chat-fab')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
expect(find.text('Loading directories…'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-create-name')),
'Draft chat',
);
await tester.enterText(
find.byKey(const Key('chat-create-instructions')),
'Keep me',
);
directories.completeError(
StateError('Server did not return chat directories.'),
);
await tester.pump();
await tester.pump();
expect(
find.textContaining('Unable to load chat options'),
findsOneWidget,
);
expect(find.text('Draft chat'), findsOneWidget);
expect(find.text('Keep me'), findsOneWidget);
gateway.directoriesHandler = () async => {
'chat_directories': ['/work'],
};
await tester.tap(find.text('Retry'));
await tester.pumpAndSettle();
expect(find.textContaining('Unable to load chat options'), findsNothing);
expect(
find.byKey(const Key('chat-create-server-directory')),
findsOneWidget,
);
expect(
find.text('New chats use the server default model.'),
findsOneWidget,
);
await tester.enterText(find.byKey(const Key('chat-create-name')), '');
await tester.tap(find.text('Create'));
await tester.pump();
expect(find.text('Enter a name and server directory.'), findsOneWidget);
expect(gateway.count('chat_create'), 0);
await tester.enterText(
find.byKey(const Key('chat-create-name')),
'Draft chat',
);
await tester.tap(find.text('Create'));
await tester.pumpAndSettle();
final fields =
gateway.lastFields('chat_create')!['chat_create']! as JsonMap;
expect(fields['title'], 'Draft chat');
expect(fields['directory'], '/work');
expect(fields.containsKey('backend'), isFalse);
expect(fields['instructions'], 'Keep me');
expect(fields.containsKey('operation_id'), isTrue);
expect(opened?['id'], 'created');
},
);
testWidgets('Cupertino create dialog keeps the draft when catalogs fail', (
tester,
) async {
final gateway = FakeChatGateway();
gateway.directoriesHandler = () =>
Future.error(StateError('Server did not return chat directories.'));
await pumpCupertinoChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-new-chat')));
await tester.pumpAndSettle();
expect(find.textContaining('Unable to load chat options'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-create-name')),
'Cupertino draft',
);
await tester.enterText(
find.byKey(const Key('chat-create-instructions')),
'Keep me too',
);
expect(find.text('Cupertino draft'), findsOneWidget);
expect(find.text('Keep me too'), findsOneWidget);
gateway.directoriesHandler = () async => {
'chat_directories': ['/work'],
};
await tester.tap(find.text('Retry'));
await tester.pumpAndSettle();
expect(find.textContaining('Unable to load chat options'), findsNothing);
expect(find.text('Cupertino draft'), findsOneWidget);
expect(find.text('Keep me too'), findsOneWidget);
});
testWidgets('material create dialog reports an empty catalog', (
tester,
) async {
final gateway = FakeChatGateway();
gateway.directoriesHandler = () async => {'chat_directories': []};
await pumpMaterialChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-new-chat-fab')));
await tester.pumpAndSettle();
expect(
find.text('The server has no chat directories or backends available.'),
findsOneWidget,
);
});
testWidgets('Cupertino create dialog uses native selectors and fields', (
tester,
) async {
final gateway = FakeChatGateway();
JsonMap? opened;
await pumpCupertinoChat(
tester,
gateway,
onOpen: (session) => opened = session,
);
await tester.tap(find.byKey(const Key('chat-new-chat')));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.text('Server directory: /work'), findsOneWidget);
expect(find.text('Backend: opencode'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-create-backend')));
await tester.pumpAndSettle();
await tester.tap(find.text('codex'));
await tester.pumpAndSettle();
expect(find.text('Backend: codex'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-create-server-directory')));
await tester.pumpAndSettle();
expect(find.text('/archive'), findsOneWidget);
await tester.tap(find.text('/archive'));
await tester.pumpAndSettle();
expect(find.text('Server directory: /archive'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-create-name')),
'Cupertino draft',
);
await tester.enterText(
find.byKey(const Key('chat-create-instructions')),
'Be careful',
);
await tester.tap(find.text('Create'));
await tester.pumpAndSettle();
final fields =
gateway.lastFields('chat_create')!['chat_create']! as JsonMap;
expect(fields['title'], 'Cupertino draft');
expect(fields['directory'], '/archive');
expect(fields['backend'], 'codex');
expect(fields['instructions'], 'Be careful');
expect(opened?['id'], 'created');
});
testWidgets('a created chat opens before the list refresh completes', (
tester,
) async {
final gateway = FakeChatGateway();
JsonMap? opened;
await pumpMaterialChat(
tester,
gateway,
onOpen: (session) => opened = session,
);
final refresh = Completer<JsonMap>();
gateway.pendingSessions.add(refresh);
await tester.tap(find.byKey(const Key('chat-new-chat-fab')));
await tester.pumpAndSettle();
await tester.tap(find.text('Create'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(gateway.count('chat_create'), 1);
expect(gateway.count('chat_sessions'), 2);
expect(
opened?['id'],
'created',
reason: 'a slow listing must not hold up opening the new chat',
);
refresh.complete({'chat_sessions': []});
await tester.pumpAndSettle();
});
}
@@ -0,0 +1,91 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
/// The message card is also mounted under a bare `MaterialApp` (the screen's
/// iOS/macOS path). Without its own style, `Text` inherits MaterialApp's
/// "missing Material" fallback: 48px, red, monospace with a double underline.
void main() {
testWidgets('Cupertino empty message under MaterialApp uses normal text', (
tester,
) async {
usePhoneSurface(tester);
await pumpIosMaterialChat(tester, FakeChatGateway());
expect(find.byType(CupertinoPageScaffold), findsOneWidget);
expect(find.byType(Scaffold), findsNothing);
const message = 'No chat sessions on this server yet.';
expect(find.text(message), findsOneWidget);
expectNormalTextStyle(tester, message);
});
testWidgets('Cupertino no-match message under MaterialApp wraps normally', (
tester,
) async {
usePhoneSurface(tester);
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpIosMaterialChat(tester, gateway);
await tester.enterText(
find.byType(CupertinoSearchTextField),
'zzz-no-match-with-a-long-query',
);
await tester.pumpAndSettle();
const message = 'No chats match "zzz-no-match-with-a-long-query".';
expect(find.text(message), findsOneWidget);
expectNormalTextStyle(tester, message);
expect(
tester.renderObject<RenderBox>(find.text(message)).size.height,
greaterThan(30),
reason: 'the query message must wrap instead of being cut to one line',
);
expect(
find.widgetWithText(CupertinoButton, 'Clear search'),
findsOneWidget,
);
});
testWidgets('Cupertino load error under MaterialApp uses normal text', (
tester,
) async {
usePhoneSurface(tester);
final gateway = FakeChatGateway()
..sessionsHandler = () => Future.error(
StateError(
'server unavailable while listing chat sessions for this operator',
),
);
await pumpIosMaterialChat(tester, gateway);
const message =
'Bad state: server unavailable while listing chat sessions '
'for this operator';
expect(find.text(message), findsOneWidget);
expectNormalTextStyle(tester, message);
expect(find.text('No chat sessions on this server yet.'), findsNothing);
expect(find.widgetWithText(CupertinoButton, 'Retry'), findsOneWidget);
});
}
/// Resolves the style actually painted for [message] and checks it is the
/// ordinary Cupertino body style rather than MaterialApp's fallback style.
void expectNormalTextStyle(WidgetTester tester, String message) {
final paragraph = tester.renderObject<RenderParagraph>(find.text(message));
final style = paragraph.text.style!;
expect(
style.fontSize,
const CupertinoThemeData().textTheme.textStyle.fontSize,
reason: 'message should not use MaterialApp\'s 48px fallback style',
);
expect(style.fontFamily, isNot('monospace'));
expect(style.fontWeight, isNot(FontWeight.w900));
expect(style.decoration, isNot(TextDecoration.underline));
expect(style.color, isNot(const Color(0xD0FF0000)));
}
@@ -0,0 +1,174 @@
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 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
void main() {
testWidgets('material row star, rename, close confirm and reopen', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-star-s2')));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_star'), {
'chat_query': {'session_id': 's2', 'starred': true},
});
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('chat-rename-field')),
' Renamed chat ',
);
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_rename'), {
'chat_rename': {'session_id': 's2', 'title': 'Renamed chat'},
});
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Close chat…'));
await tester.pumpAndSettle();
expect(find.text('Close chat?'), findsOneWidget);
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(gateway.count('chat_close'), 0);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Close chat…'));
await tester.pumpAndSettle();
await tester.tap(find.text('Close chat'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_close'), {
'chat_query': {'session_id': 's2'},
});
await tester.ensureVisible(find.byKey(const Key('chat-actions-s4')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-actions-s4')));
await tester.pumpAndSettle();
await tester.tap(find.text('Reopen'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_reopen'), {
'chat_query': {'session_id': 's4'},
});
});
testWidgets('Cupertino close confirmation uses the action sheet flow', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Close chat…'));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(
find.textContaining('marks it closed on every device'),
findsOneWidget,
);
await tester.tap(find.text('Close chat'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_close'), {
'chat_query': {'session_id': 's2'},
});
});
testWidgets('material rename disables Save while the name is blank', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('chat-rename-field')), ' ');
await tester.pump();
final save = tester.widget<FilledButton>(
find.widgetWithText(FilledButton, 'Save'),
);
expect(save.onPressed, isNull);
expect(gateway.count('chat_rename'), 0);
});
testWidgets('Cupertino rename disables Save while the name is blank', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('chat-rename-field')), ' ');
await tester.pump();
final save = tester.widget<CupertinoDialogAction>(
find.widgetWithText(CupertinoDialogAction, 'Save'),
);
expect(save.onPressed, isNull);
expect(gateway.count('chat_rename'), 0);
});
testWidgets('material rename helper wraps instead of truncating at 2x', (
tester,
) async {
usePhoneSurface(tester);
tester.platformDispatcher.textScaleFactorTestValue = 2;
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
const helper = 'This name is shared with every device.';
expect(find.text(helper), findsOneWidget);
expect(
tester.widget<Text>(find.text(helper)).maxLines,
2,
reason: 'helperMaxLines defaults to one, which truncates the sentence',
);
expect(tester.takeException(), isNull);
});
testWidgets('opening a row calls onOpen with the server session', (
tester,
) async {
JsonMap? opened;
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(
tester,
gateway,
onOpen: (session) => opened = session,
);
await tester.tap(find.byKey(const Key('chat-row-s2')));
await tester.pumpAndSettle();
expect(opened?['id'], 's2');
});
}
@@ -0,0 +1,76 @@
import 'dart:async';
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/ui/sessions/chat_sessions_screen.dart';
import 'fake_chat_gateway.dart';
void main() {
testWidgets('a stale refresh reply never replaces the latest listing', (
tester,
) async {
final gateway = FakeChatGateway();
final first = Completer<JsonMap>();
final second = Completer<JsonMap>();
gateway.pendingSessions.addAll([first, second]);
await tester.pumpWidget(
MaterialApp(
home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}),
),
);
await tester.pump();
await tester.tap(find.byKey(const Key('chat-refresh')));
await tester.pump();
expect(gateway.count('chat_sessions'), 2);
second.complete({
'chat_sessions': [
{'id': 'new', 'title': 'Newest chat'},
],
});
await tester.pump();
await tester.pump();
expect(find.text('Newest chat'), findsOneWidget);
first.complete({
'chat_sessions': [
{'id': 'old', 'title': 'Older chat'},
],
});
await tester.pump();
await tester.pump();
expect(find.text('Older chat'), findsNothing);
expect(find.text('Newest chat'), findsOneWidget);
});
testWidgets('a reply completing after dispose changes nothing', (
tester,
) async {
final gateway = FakeChatGateway();
final pending = Completer<JsonMap>();
gateway.pendingSessions.add(pending);
await tester.pumpWidget(
MaterialApp(
home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}),
),
);
await tester.pump();
await tester.pumpWidget(const MaterialApp(home: SizedBox()));
pending.complete({
'chat_sessions': [
{'id': 'late', 'title': 'Late chat'},
],
});
await tester.pump();
await tester.pump();
expect(tester.takeException(), isNull);
expect(find.text('Late chat'), findsNothing);
});
}
@@ -0,0 +1,213 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
void main() {
testWidgets(
'material list keeps closed starred rows once and groups directories once',
(tester) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
expect(find.text('Starred'), findsOneWidget);
expect(find.text('Chats'), findsNWidgets(2));
expect(find.text('Closed'), findsOneWidget);
expect(find.text('Starred chat'), findsOneWidget);
expect(find.text('Starred closed'), findsOneWidget);
expect(find.text('Open chat'), findsOneWidget);
expect(find.byIcon(Icons.folder_outlined), findsNWidgets(4));
expect(find.byType(Scaffold), findsOneWidget);
},
);
testWidgets('material search distinguishes no-match and clears back', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
await tester.enterText(find.byType(TextField), 'zzz');
await tester.pumpAndSettle();
expect(find.text('No chats match "zzz".'), findsOneWidget);
expect(find.text('Open chat'), findsNothing);
await tester.tap(find.text('Clear search'));
await tester.pumpAndSettle();
expect(find.text('Open chat'), findsOneWidget);
});
testWidgets('material empty server shows the distinct empty message', (
tester,
) async {
final gateway = FakeChatGateway();
await pumpMaterialChat(tester, gateway);
expect(find.text('No chat sessions on this server yet.'), findsOneWidget);
expect(find.textContaining('No chats match'), findsNothing);
});
testWidgets(
'Cupertino app renders standard controls, groups and renames without Material',
(tester) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
expect(find.byType(CupertinoPageScaffold), findsOneWidget);
expect(find.byType(CupertinoSearchTextField), findsOneWidget);
expect(find.byType(Scaffold), findsNothing);
expect(
tester.getTopLeft(find.byType(CupertinoSearchTextField)).dy,
greaterThanOrEqualTo(
tester.getBottomLeft(find.byType(CupertinoNavigationBar)).dy,
),
);
expect(find.text('Chats · /work'), findsOneWidget);
expect(find.text('Chats · /else'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-star-s2')));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_star'), {
'chat_query': {'session_id': 's2', 'starred': true},
});
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
expect(find.text('Rename…'), findsOneWidget);
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-rename-field')),
'Renamed on Cupertino',
);
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_rename'), {
'chat_rename': {'session_id': 's2', 'title': 'Renamed on Cupertino'},
});
await tester.tap(find.byKey(const Key('chat-actions-s4')));
await tester.pumpAndSettle();
await tester.tap(find.text('Reopen'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_reopen'), {
'chat_query': {'session_id': 's4'},
});
},
);
testWidgets(
'Cupertino no-match message wraps and Clear search is its own button',
(tester) async {
usePhoneSurface(tester);
final semantics = tester.ensureSemantics();
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
const query = 'zzz-no-match-with-a-long-query';
await tester.enterText(find.byType(CupertinoSearchTextField), query);
await tester.pumpAndSettle();
const message = 'No chats match "zzz-no-match-with-a-long-query".';
expect(find.text(message), findsOneWidget);
expect(find.text('Open chat'), findsNothing);
final messageBox = tester.renderObject<RenderBox>(find.text(message));
expect(
messageBox.size.height,
greaterThan(30),
reason: 'the query message must wrap instead of being cut to one line',
);
final clear = find.bySemanticsLabel('Clear search');
expect(clear, findsOneWidget);
expect(tester.getSemantics(clear).label, 'Clear search');
await tester.tap(find.text('Clear search'));
await tester.pumpAndSettle();
expect(find.text('Open chat'), findsOneWidget);
semantics.dispose();
},
);
testWidgets(
'Cupertino load failure wraps the reason and hides the empty message',
(tester) async {
usePhoneSurface(tester);
final gateway = FakeChatGateway()
..sessionsHandler = () => Future.error(
StateError(
'server unavailable while listing chat sessions for this operator',
),
);
await pumpCupertinoChat(tester, gateway);
const message =
'Bad state: server unavailable while listing chat sessions '
'for this operator';
expect(find.text(message), findsOneWidget);
expect(find.text('No chat sessions on this server yet.'), findsNothing);
final messageBox = tester.renderObject<RenderBox>(find.text(message));
expect(
messageBox.size.height,
greaterThan(30),
reason: 'the server reason must wrap instead of being cut to one line',
);
expect(find.widgetWithText(CupertinoButton, 'Retry'), findsOneWidget);
},
);
testWidgets('Cupertino no-match message survives 2x text scaling', (
tester,
) async {
usePhoneSurface(tester);
tester.platformDispatcher.textScaleFactorTestValue = 2;
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
await tester.enterText(
find.byType(CupertinoSearchTextField),
'zzz-no-match-with-a-long-query',
);
await tester.pumpAndSettle();
expect(
find.text('No chats match "zzz-no-match-with-a-long-query".'),
findsOneWidget,
);
expect(find.text('Clear search'), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('duplicate Cupertino titles disambiguate the action labels', (
tester,
) async {
final semantics = tester.ensureSemantics();
final gateway = FakeChatGateway()
..sessionsReply = {
'chat_sessions': [
{'id': 'd1', 'title': 'New chat', 'directory': '/work'},
{'id': 'd2', 'title': 'New chat', 'directory': '/work'},
],
};
await pumpCupertinoChat(tester, gateway);
expect(
tester.getSemantics(find.byKey(const Key('chat-actions-d1'))).label,
'Chat actions for New chat (d1)',
);
expect(
tester.getSemantics(find.byKey(const Key('chat-actions-d2'))).label,
'Chat actions for New chat (d2)',
);
semantics.dispose();
});
}
@@ -0,0 +1,77 @@
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/ui/sessions/chat_sessions_screen.dart';
import 'fake_chat_gateway.dart';
List<JsonMap> sampleSessions() => [
{'id': 's1', 'title': 'Starred chat', 'directory': '/work', 'starred': true},
{'id': 's2', 'title': 'Open chat', 'directory': '/work'},
{'id': 's3', 'title': 'Elsewhere chat', 'directory': '/else'},
{
'id': 's4',
'title': 'Closed chat',
'directory': '/else',
'closed_at': '2026-01-01',
},
{
'id': 's5',
'title': 'Starred closed',
'directory': '/work',
'starred': true,
'closed_at': '2026-01-02',
},
];
Future<void> pumpMaterialChat(
WidgetTester tester,
FakeChatGateway gateway, {
ValueChanged<JsonMap>? onOpen,
}) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
),
);
await tester.pumpAndSettle();
}
Future<void> pumpCupertinoChat(
WidgetTester tester,
FakeChatGateway gateway, {
ValueChanged<JsonMap>? onOpen,
}) async {
await tester.pumpWidget(
CupertinoApp(
home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
),
);
await tester.pumpAndSettle();
}
/// The screen's iOS/macOS path: Cupertino controls under the app's ordinary
/// `MaterialApp` root, with no Material or CupertinoTheme ancestor.
Future<void> pumpIosMaterialChat(
WidgetTester tester,
FakeChatGateway gateway, {
ValueChanged<JsonMap>? onOpen,
}) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.iOS),
home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
),
);
await tester.pumpAndSettle();
}
/// Narrows the test surface to a phone so long messages must wrap.
void usePhoneSurface(WidgetTester tester) {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
}
@@ -0,0 +1,56 @@
import 'dart:async';
import 'dart:collection';
import 'package:pipelines_app/core/api_gateway.dart';
/// Scripted gateway for session-browser widget tests.
class FakeChatGateway implements ApiGateway {
final calls = <({String type, JsonMap fields})>[];
final pendingSessions = Queue<Completer<JsonMap>>();
JsonMap sessionsReply = const {'chat_sessions': []};
Future<JsonMap> Function()? sessionsHandler;
JsonMap createReply = const {
'chat_session': {'id': 'created', 'title': 'New chat'},
};
Future<JsonMap> Function()? directoriesHandler;
Future<JsonMap> Function()? backendsHandler;
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
calls.add((type: type, fields: fields));
switch (type) {
case 'chat_sessions':
if (pendingSessions.isNotEmpty) {
return pendingSessions.removeFirst().future;
}
if (sessionsHandler != null) return sessionsHandler!();
return Future.value(sessionsReply);
case 'chat_directories':
return directoriesHandler?.call() ??
Future.value(const {
'chat_directories': ['/work', '/archive'],
});
case 'chat_backends':
return backendsHandler?.call() ??
Future.value(const {
'chat_backends': ['opencode', 'codex'],
});
case 'chat_create':
return Future.value(createReply);
default:
return Future.value(const {});
}
}
int count(String type) => calls.where((call) => call.type == type).length;
JsonMap? lastFields(String type) {
for (final call in calls.reversed) {
if (call.type == type) return call.fields;
}
return null;
}
}
@@ -0,0 +1,229 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
import 'graph_fixtures.dart';
void main() {
group('outcome and edge order', () {
test('success first, other outcomes alphabetical, error last', () {
expect(
stageOutcomes(
stage(
'a',
edges: <String, String?>{
'error': '#',
'rejected': 'a',
'success': 'b',
'approved': 'b',
'retry': 'a',
},
),
),
<String>['success', 'approved', 'rejected', 'retry', 'error'],
);
expect(stageOutcomes(<String, dynamic>{}), isEmpty);
expect(stageOutcomes(null), isEmpty);
});
test('edgeLabel marks only an implicit fallback error route', () {
expect(
edgeLabel(<String, dynamic>{'fallback_error': true}, 'error'),
'error*',
);
expect(
edgeLabel(<String, dynamic>{'fallback_error': false}, 'error'),
'error',
);
expect(
edgeLabel(<String, dynamic>{'fallback_error': true}, 'success'),
'success',
);
expect(edgeLabel(<String, dynamic>{}, 'rejected'), 'rejected');
});
});
group('linear definition', () {
test('edges keep stage and outcome order with contiguous ids', () {
final edges = graphEdges(linearGraph());
expect(edges.map((edge) => edge.id), <int>[1, 2, 3, 4, 5]);
expect(edges.map((edge) => edge.source), <String>[
'plan',
'plan',
'build',
'ship',
'ship',
]);
expect(edges.map((edge) => edge.outcome), <String>[
'success',
'error',
'success',
'success',
'error',
]);
expect(edges.map((edge) => edge.target), <String>[
'build',
'#failure',
'ship',
'#success',
'#failure',
]);
expect(edges.map((edge) => edge.label), <String>[
'success',
'error*',
'success',
'success',
'error',
]);
expect(edges.where((edge) => edge.fallback).map((edge) => edge.id), <int>[
2,
]);
expect(edges.every((edge) => edge.knownTarget), isTrue);
});
test('nodes are declaration order plus failure then success terminals', () {
final nodes = graphNodes(linearGraph());
expect(nodes.map((node) => node.key), <String>[
'plan',
'build',
'ship',
failureEnd,
successEnd,
]);
expect(nodes.map((node) => node.stageIndex), <int?>[0, 1, 2, null, null]);
expect(nodes.map((node) => node.terminal), <bool>[
false,
false,
false,
true,
true,
]);
expect(nodes[3].label, 'Failure');
expect(nodes[3].shortLabel, 'FAILURE');
expect(nodes[4].label, 'Success');
expect(nodes[4].shortLabel, 'SUCCESS');
});
});
group('diamond definition', () {
test('keeps every converging edge distinct in stable order', () {
final edges = graphEdges(diamondGraph());
expect(
edges.map((edge) => '${edge.source}/${edge.outcome}->${edge.target}'),
<String>[
'a/success->b',
'a/approved->c',
'a/error->#failure',
'b/success->d',
'c/success->d',
'd/success->#success',
],
);
expect(edges.every((edge) => edge.knownTarget), isTrue);
});
});
group('self loops', () {
test('a self edge is one edge and never duplicates node identity', () {
final graph = selfLoopGraph();
final edges = graphEdges(graph);
expect(
edges.map((edge) => '${edge.source}/${edge.outcome}->${edge.target}'),
<String>[
'a/success->b',
'a/retry->a',
'b/success->#success',
'b/error->#failure',
],
);
expect(edges[1].source, edges[1].target);
expect(edges[1].knownTarget, isTrue);
final nodes = graphNodes(graph);
expect(nodes.map((node) => node.key), <String>[
'a',
'b',
failureEnd,
successEnd,
]);
expect(nodes.where((node) => node.key == 'a'), hasLength(1));
});
test(
'a stage declared twice keeps one node and one set of edges per key',
() {
final graph = <String, dynamic>{
'stages': <dynamic>[
stage('a', edges: <String, String?>{'retry': 'a'}),
stage('a', edges: <String, String?>{'success': '#success'}),
],
};
expect(graphNodes(graph).map((node) => node.key), <String>[
'a',
failureEnd,
successEnd,
]);
// Both declarations are still definition data, with unique edge ids.
expect(graphEdges(graph).map((edge) => edge.id), <int>[1, 2]);
},
);
});
group('missing and unknown targets', () {
test(
'an absent edge declares nothing; empty and unknown targets stay honest',
() {
final edges = graphEdges(incompleteGraph());
expect(edges.map((edge) => edge.id), <int>[1, 2, 3, 4]);
expect(edges.map((edge) => edge.outcome), <String>[
'blocked',
'retry',
'error',
'success',
]);
expect(edges[0].target, '');
expect(edges[0].knownTarget, isFalse);
expect(edges[1].target, 'ghost');
expect(edges[1].knownTarget, isFalse);
expect(edges[2].target, failureEnd);
expect(edges[2].fallback, isTrue);
expect(edges[3].target, successEnd);
},
);
test('an unknown target does not become a node or a terminal', () {
final graph = <String, dynamic>{
'stages': <dynamic>[
stage('a', edges: <String, String?>{'retry': 'ghost'}),
],
};
expect(graphNodes(graph).map((node) => node.key), <String>['a']);
expect(graphEdges(graph).single.knownTarget, isFalse);
});
test('a graph with no stages has no nodes or edges', () {
expect(graphNodes(<String, dynamic>{}), isEmpty);
expect(graphEdges(<String, dynamic>{'stages': null}), isEmpty);
expect(graphNodes(null), isEmpty);
});
});
test(
'definition nodes ignore run evidence even when the graph map carries it',
() {
final graph = <String, dynamic>{
'stages': <dynamic>[
stage('a', edges: <String, String?>{'success': 'b'}),
stage('b'),
],
'steps': <dynamic>[
step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'),
],
'visited_stages': <String>['a', 'b'],
};
final nodes = graphNodes(graph);
expect(nodes.map((node) => node.key), <String>['a', 'b']);
expect(nodes.every((node) => !node.terminal), isTrue);
},
);
}
@@ -0,0 +1,96 @@
import 'package:pipelines_app/core/api_gateway.dart';
/// Small, server-shaped fixtures shared by the graph domain tests.
JsonMap step({
int sequence = 0,
String stage = '',
String status = 'completed',
String outcome = '',
String target = '',
String startedAt = '',
Map<String, dynamic>? control,
}) {
return <String, dynamic>{
'sequence': sequence,
'stage': stage,
'status': status,
'outcome': outcome,
'target': target,
if (startedAt.isNotEmpty) 'started_at': startedAt,
'control': ?control,
};
}
JsonMap stage(
String key, {
Map<String, String?> edges = const {},
bool fallbackError = false,
String type = 'model',
}) {
return <String, dynamic>{
'key': key,
'type': type,
'edges': edges,
if (fallbackError) 'fallback_error': true,
};
}
/// plan -> build -> ship, with an implicit failure fallback on plan and an
/// explicit terminal pair on ship.
JsonMap linearGraph() => <String, dynamic>{
'stages': <dynamic>[
stage(
'plan',
edges: <String, String?>{'success': 'build', 'error': '#'},
fallbackError: true,
),
stage('build', edges: <String, String?>{'success': 'ship'}),
stage(
'ship',
edges: <String, String?>{'success': '#success', 'error': '#failure'},
),
],
};
/// a fans out to b/c and both converge on d.
JsonMap diamondGraph() => <String, dynamic>{
'stages': <dynamic>[
stage(
'a',
edges: <String, String?>{'success': 'b', 'approved': 'c', 'error': '#'},
fallbackError: true,
),
stage('b', edges: <String, String?>{'success': 'd'}),
stage('c', edges: <String, String?>{'success': 'd'}),
stage('d', edges: <String, String?>{'success': '#success'}),
],
};
/// a retries itself and can still succeed into b; terminal pair on b.
JsonMap selfLoopGraph() => <String, dynamic>{
'stages': <dynamic>[
stage('a', edges: <String, String?>{'success': 'b', 'retry': 'a'}),
stage(
'b',
edges: <String, String?>{'success': '#success', 'error': '#failure'},
),
],
};
/// A definition with an absent edge, an empty target and an unknown target.
JsonMap incompleteGraph() => <String, dynamic>{
'stages': <dynamic>[
stage(
'a',
edges: <String, String?>{
'success': null,
'blocked': '',
'retry': 'ghost',
'error': '#',
},
fallbackError: true,
),
stage('b', edges: <String, String?>{'success': '#success'}),
],
};
@@ -0,0 +1,56 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
void main() {
group('terminal target normalization', () {
test('a bare # resolves by outcome exactly like the web protocol', () {
expect(resolveTarget('error', '#'), failureEnd);
expect(resolveTarget('success', '#'), successEnd);
expect(resolveTarget('approved', '#'), successEnd);
expect(resolveTarget('', '#'), successEnd);
});
test('explicit, empty and unknown targets are preserved verbatim', () {
expect(resolveTarget('success', successEnd), successEnd);
expect(resolveTarget('error', failureEnd), failureEnd);
expect(resolveTarget('success', 'review'), 'review');
expect(resolveTarget('blocked', ''), '');
expect(resolveTarget('retry', 'ghost'), 'ghost');
expect(resolveTarget('success', ' #success'), ' #success');
});
test(
'a missing target stays missing instead of fabricating a terminal',
() {
expect(resolveTarget('success', null), isNull);
expect(resolveTarget(null, null), isNull);
},
);
test('only the explicit terminal keys are terminals', () {
expect(isTerminalTarget(successEnd), isTrue);
expect(isTerminalTarget(failureEnd), isTrue);
expect(isTerminalTarget('#'), isFalse);
expect(isTerminalTarget('review'), isFalse);
expect(isTerminalTarget(''), isFalse);
expect(isTerminalTarget(null), isFalse);
});
});
group('terminal labels', () {
test('TUI labels are SUCCESS and FAILURE', () {
expect(nodeLabel(successEnd), 'SUCCESS');
expect(nodeLabel(failureEnd), 'FAILURE');
expect(nodeLabel('implementer'), 'implementer');
expect(nodeLabel(''), '');
expect(nodeLabel(null), '');
});
test('display labels title-case the terminals and keep stage keys', () {
expect(nodeDisplayLabel(successEnd), 'Success');
expect(nodeDisplayLabel(failureEnd), 'Failure');
expect(nodeDisplayLabel('implementer'), 'implementer');
expect(nodeDisplayLabel(null), '');
});
});
}
@@ -0,0 +1,91 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/run_graph_state.dart';
import 'graph_fixtures.dart';
void main() {
group('current stage fallback', () {
test('the run current stage wins over the last recorded visit', () {
final state = runGraphState(<String, dynamic>{
'current_stage': 'committer',
'steps': <dynamic>[step(sequence: 1, stage: 'review')],
});
expect(state.currentStage, 'committer');
});
test('a blank current stage falls back to the last visit, else null', () {
final fallback = runGraphState(<String, dynamic>{
'current_stage': ' ',
'steps': <dynamic>[
step(sequence: 1, stage: 'a'),
step(sequence: 2, stage: 'b'),
],
});
expect(fallback.currentStage, 'b');
final blankLast = runGraphState(<String, dynamic>{
'steps': <dynamic>[step(sequence: 1)],
});
expect(blankLast.currentStage, isNull);
});
});
group('active stage and start', () {
test('a live run exposes its running visit start', () {
final state = runGraphState(<String, dynamic>{
'executing': true,
'current_stage': 'review',
'steps': <dynamic>[
step(
sequence: 1,
stage: 'review',
status: 'running',
startedAt: '2026-01-01T00:00:00Z',
),
],
});
expect(state.executing, isTrue);
expect(state.activeStage, 'review');
expect(state.currentStageStartedAt, '2026-01-01T00:00:00Z');
});
test('a finished run has no active stage or start', () {
final state = runGraphState(<String, dynamic>{
'executing': false,
'current_stage': 'review',
'steps': <dynamic>[
step(
sequence: 1,
stage: 'review',
status: 'running',
startedAt: '2026-01-01T00:00:00Z',
),
],
});
expect(state.activeStage, isNull);
expect(state.currentStageStartedAt, isNull);
});
test('only an exact running status with a non-blank start is used', () {
final state = runGraphState(<String, dynamic>{
'executing': true,
'current_stage': 'review',
'steps': <dynamic>[
step(
sequence: 1,
stage: 'review',
status: 'Running',
startedAt: '2026-01-01T00:00:00Z',
),
step(
sequence: 2,
stage: 'review',
status: 'running',
startedAt: ' ',
),
],
});
expect(state.currentStageStartedAt, isNull);
});
});
}
@@ -0,0 +1,170 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
import 'package:pipelines_app/features/graph/domain/run_graph_state.dart';
import 'graph_fixtures.dart';
void main() {
group('linear run evidence', () {
test('visits and routes follow the recorded visits', () {
final state = runGraphState(<String, dynamic>{
'executing': false,
'steps': <dynamic>[
step(sequence: 1, stage: 'plan', outcome: 'success', target: 'build'),
step(sequence: 2, stage: 'build', outcome: 'success', target: 'ship'),
step(
sequence: 3,
stage: 'ship',
outcome: 'success',
target: '#success',
),
],
});
expect(state.visitedStages, <String>[
'plan',
'build',
'ship',
successEnd,
]);
expect(state.takenRoutes, <String>[
'plan\u0000success\u0000build',
'build\u0000success\u0000ship',
'ship\u0000success\u0000#success',
]);
expect(state.currentStage, 'ship');
expect(state.executing, isFalse);
expect(state.currentStageStartedAt, isNull);
expect(state.activeStage, isNull);
});
});
group('diamond run evidence', () {
test('repeated visits keep one identity and loop routes stay distinct', () {
final state = runGraphState(<String, dynamic>{
'executing': false,
'steps': <dynamic>[
step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'),
step(sequence: 2, stage: 'b', outcome: 'success', target: 'd'),
step(sequence: 3, stage: 'd', outcome: 'rejected', target: 'b'),
step(sequence: 4, stage: 'b', outcome: 'success', target: 'd'),
step(sequence: 5, stage: 'd', outcome: 'success', target: '#success'),
],
});
expect(state.visitedStages, <String>['a', 'b', 'd', successEnd]);
expect(state.visitedStages.where((key) => key == 'b'), hasLength(1));
expect(state.takenRoutes, <String>[
'a\u0000success\u0000b',
'b\u0000success\u0000d',
'd\u0000rejected\u0000b',
'd\u0000success\u0000#success',
]);
});
test('different outcomes to the same target stay separate routes', () {
final state = runGraphState(<String, dynamic>{
'executing': false,
'steps': <dynamic>[
step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'),
step(sequence: 2, stage: 'a', outcome: 'approved', target: 'b'),
step(sequence: 3, stage: 'a', outcome: 'success', target: 'b'),
],
});
expect(state.visitedStages, <String>['a']);
expect(state.takenRoutes, <String>[
'a\u0000success\u0000b',
'a\u0000approved\u0000b',
]);
});
});
group('self edges', () {
test('a self edge is evidence, not a second visit or recursion', () {
final state = runGraphState(<String, dynamic>{
'executing': false,
'steps': <dynamic>[
step(sequence: 1, stage: 'a', outcome: 'retry', target: 'a'),
step(sequence: 2, stage: 'a', outcome: 'success', target: 'b'),
],
});
expect(state.visitedStages, <String>['a']);
expect(state.takenRoutes, <String>[
'a\u0000retry\u0000a',
'a\u0000success\u0000b',
]);
});
});
group('terminals', () {
test('a bare # resolves to failure on error and success otherwise', () {
final failed = runGraphState(<String, dynamic>{
'steps': <dynamic>[
step(sequence: 1, stage: 'impl', outcome: 'error', target: '#'),
],
});
expect(failed.visitedStages, <String>['impl', failureEnd]);
expect(failed.visitedStages, isNot(contains(successEnd)));
expect(failed.isRouteTaken('impl', 'error', '#'), isTrue);
final succeeded = runGraphState(<String, dynamic>{
'steps': <dynamic>[
step(sequence: 1, stage: 'impl', outcome: 'done', target: '#'),
],
});
expect(succeeded.visitedStages, <String>['impl', successEnd]);
expect(succeeded.visitedStages, isNot(contains(failureEnd)));
});
test('a non-terminal target is not visited until a step lands on it', () {
final state = runGraphState(<String, dynamic>{
'steps': <dynamic>[
step(
sequence: 1,
stage: 'impl',
outcome: 'success',
target: 'review',
),
],
});
expect(state.visitedStages, <String>['impl']);
expect(state.isStageVisited('review'), isFalse);
expect(state.isRouteTaken('impl', 'success', 'review'), isTrue);
});
test('blank outcome or target records no route and no terminal visit', () {
final state = runGraphState(<String, dynamic>{
'steps': <dynamic>[
step(sequence: 1, stage: 'impl', outcome: 'success', target: ''),
step(sequence: 2, stage: 'impl', outcome: '', target: '#success'),
],
});
expect(state.visitedStages, <String>['impl']);
expect(state.takenRoutes, isEmpty);
});
});
group('missing evidence', () {
test('absent run or steps fabricates no visits', () {
for (final run in <dynamic>[
null,
<String, dynamic>{},
<String, dynamic>{'steps': null},
<String, dynamic>{'steps': <dynamic>[]},
]) {
final state = runGraphState(run);
expect(state.visitedStages, isEmpty);
expect(state.takenRoutes, isEmpty);
expect(state.currentStage, isNull);
expect(state.executing, isFalse);
expect(state.currentStageStartedAt, isNull);
}
});
test('malformed step entries are ignored, not invented', () {
final state = runGraphState(<String, dynamic>{
'steps': <dynamic>['nope', 42, null],
});
expect(state.visitedStages, isEmpty);
expect(state.takenRoutes, isEmpty);
});
});
}
@@ -0,0 +1,150 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/stage_visits.dart';
import 'graph_fixtures.dart';
void main() {
group('ordered stage visits', () {
test('repeated visits are ordered by sequence, not input order', () {
final steps = <dynamic>[
step(
sequence: 5,
stage: 'review',
outcome: 'rejected',
target: 'implementer',
control: <String, dynamic>{'visit': 2},
),
step(sequence: 3, stage: 'implementer'),
step(
sequence: 2,
stage: 'review',
outcome: 'success',
target: 'done',
control: <String, dynamic>{'visit': 1},
),
].cast<Map<String, dynamic>>();
final byStage = visitsByStage(steps);
expect(byStage.keys, <String>['review', 'implementer']);
expect(byStage['review']!.map((visit) => visit['sequence']), <int>[2, 5]);
expect(byStage['review']!.map((visit) => visit['outcome']), <String>[
'success',
'rejected',
]);
expect(displayVisit(byStage['review']![0], 0), 1);
expect(displayVisit(byStage['review']![1], 1), 2);
});
test('equal sequences keep their recorded order', () {
final steps = <dynamic>[
step(sequence: 1, stage: 'a', outcome: 'first'),
step(sequence: 1, stage: 'a', outcome: 'second'),
].cast<Map<String, dynamic>>();
expect(
visitsByStage(steps)['a']!.map((visit) => visit['outcome']),
<String>['first', 'second'],
);
});
test('a missing control visit falls back to the position', () {
final steps = <dynamic>[
step(sequence: 1, stage: 'a'),
step(sequence: 2, stage: 'a'),
].cast<Map<String, dynamic>>();
final visits = visitsByStage(steps)['a']!;
expect(displayVisit(visits[0], 0), 1);
expect(displayVisit(visits[1], 1), 2);
});
test(
'a non-positive or malformed control visit falls back to position',
() {
expect(
displayVisit(step(control: <String, dynamic>{'visit': 0}), 2),
3,
);
expect(
displayVisit(step(control: <String, dynamic>{'visit': -1}), 2),
3,
);
expect(
displayVisit(step(control: <String, dynamic>{'visit': '3'}), 0),
3,
);
expect(displayVisit(step(), 4), 5);
},
);
});
group('clamping', () {
test('keeps a valid index and handles an empty list', () {
expect(clampVisitIndex(0, 3), 0);
expect(clampVisitIndex(2, 3), 2);
expect(clampVisitIndex(99, 3), 2);
expect(clampVisitIndex(-4, 3), 0);
expect(clampVisitIndex(5, 0), 0);
});
});
group('selection', () {
List<Map<String, dynamic>> repeatedVisits() => <dynamic>[
step(sequence: 5, stage: 'review', outcome: 'rejected'),
step(sequence: 2, stage: 'review', outcome: 'success'),
].cast<Map<String, dynamic>>();
test('no requested visit selects the stage most recent recorded visit', () {
final selection = selectStageVisit(repeatedVisits(), 'review');
expect(selection.hasVisit, isTrue);
expect(selection.index, 1);
expect(selection.step!['sequence'], 5);
expect(selection.visitNumber, 2);
});
test('an explicit visit selects that recorded visit', () {
final selection = selectStageVisit(
repeatedVisits(),
'review',
visitIndex: 0,
);
expect(selection.step!['sequence'], 2);
expect(selection.visitNumber, 1);
});
test('out-of-range indexes clamp to the nearest recorded visit', () {
final late = selectStageVisit(repeatedVisits(), 'review', visitIndex: 99);
expect(late.index, 1);
expect(late.step!['sequence'], 5);
expect(late.correctedRequest(99), isTrue);
final early = selectStageVisit(
repeatedVisits(),
'review',
visitIndex: -4,
);
expect(early.index, 0);
expect(early.step!['sequence'], 2);
expect(early.correctedRequest(-4), isTrue);
expect(early.correctedRequest(null), isFalse);
});
test('a stage with no recorded visit returns no fabricated step', () {
final selection = selectStageVisit(repeatedVisits(), 'never-ran');
expect(selection.hasVisit, isFalse);
expect(selection.step, isNull);
expect(selection.index, 0);
expect(selection.visitNumber, 0);
final empty = selectStageVisit(const <Map<String, dynamic>>[], 'review');
expect(empty.hasVisit, isFalse);
expect(empty.step, isNull);
});
test('an absent capture for one stage does not hide another stage', () {
final steps = <dynamic>[
step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'),
].cast<Map<String, dynamic>>();
expect(selectStageVisit(steps, 'a').hasVisit, isTrue);
expect(selectStageVisit(steps, 'b').hasVisit, isFalse);
});
});
}
@@ -0,0 +1,96 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart';
import 'package:pipelines_app/features/graph/layout/layout_models.dart';
import 'layout_fixtures.dart';
/// Invalid and boundary input for the pure layout engine.
void main() {
test('an empty definition yields empty padded bounds', () {
final layout = layoutGraphNodes(
nodes: const <GraphNode>[],
edges: const <GraphEdge>[],
extents: const <String, NodeExtent>{},
config: layoutConfig(columnGap: 30, rowGap: 10, padding: 6),
);
expect(layout.isEmpty, isTrue);
expect(layout.rankCount, 0);
expect(layout.width, 12);
expect(layout.height, 12);
expect(layout.ranks, isEmpty);
});
test('missing measurements are reported rather than invented', () {
final graph = linearGraphFixture();
final nodes = graphNodes(graph);
final extents = uniformExtents(nodes)..remove('build');
expect(
() => layoutGraphNodes(
nodes: nodes,
edges: graphEdges(graph),
extents: extents,
config: layoutConfig(),
),
throwsArgumentError,
);
});
test('extra measurements are ignored because they cannot become nodes', () {
final graph = linearGraphFixture();
final nodes = graphNodes(graph);
final extents = uniformExtents(nodes)
..['ghost'] = NodeExtent(width: 20, height: 20);
final layout = layoutGraphNodes(
nodes: nodes,
edges: graphEdges(graph),
extents: extents,
config: layoutConfig(),
);
expect(layout.nodeFor('ghost'), isNull);
expect(layout.nodes.length, nodes.length);
});
test('duplicate or empty node keys are rejected', () {
const stageNode = GraphNode(key: 'a', terminal: false, stageIndex: 0);
expect(
() => layoutGraphNodes(
nodes: const <GraphNode>[stageNode, stageNode],
edges: const <GraphEdge>[],
extents: <String, NodeExtent>{'a': NodeExtent(width: 10, height: 10)},
config: layoutConfig(),
),
throwsArgumentError,
);
expect(
() => layoutGraphNodes(
nodes: const <GraphNode>[
GraphNode(key: '', terminal: false, stageIndex: 0),
],
edges: const <GraphEdge>[],
extents: const <String, NodeExtent>{},
config: layoutConfig(),
),
throwsArgumentError,
);
});
test('invalid gaps and extents are rejected', () {
expect(
() => GraphLayoutConfig(columnGap: -1, rowGap: 8),
throwsArgumentError,
);
expect(
() => GraphLayoutConfig(columnGap: 8, rowGap: double.nan),
throwsArgumentError,
);
expect(
() => NodeExtent(width: double.infinity, height: 10),
throwsArgumentError,
);
});
}
@@ -0,0 +1,228 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart';
import 'package:pipelines_app/features/graph/layout/layout_models.dart';
import 'layout_fixtures.dart';
GraphLayout _layout(
Map<String, dynamic> graph, {
Map<String, NodeExtent>? extents,
GraphLayoutConfig? config,
}) {
final nodes = graphNodes(graph);
return layoutGraphNodes(
nodes: nodes,
edges: graphEdges(graph),
extents: extents ?? uniformExtents(nodes),
config: config ?? layoutConfig(),
);
}
void _expectWithinBounds(GraphLayout layout) {
for (final box in layout.nodes) {
expect(box.x, greaterThanOrEqualTo(0), reason: '${box.key} left');
expect(box.y, greaterThanOrEqualTo(0), reason: '${box.key} top');
expect(
box.right,
lessThanOrEqualTo(layout.width),
reason: '${box.key} right inside width',
);
expect(
box.bottom,
lessThanOrEqualTo(layout.height),
reason: '${box.key} bottom inside height',
);
}
}
void _expectSeparated(GraphLayout layout) {
for (var first = 0; first < layout.nodes.length; first += 1) {
for (var second = first + 1; second < layout.nodes.length; second += 1) {
final a = layout.nodes[first];
final b = layout.nodes[second];
final separated =
a.right <= b.x ||
b.right <= a.x ||
a.bottom <= b.y ||
b.bottom <= a.y;
expect(separated, isTrue, reason: '${a.key} overlaps ${b.key}');
}
}
}
void main() {
test('linear nodes keep declaration order and terminal identity', () {
final layout = _layout(linearGraphFixture());
expect(layout.rankCount, 4);
expect(layout.nodes.map((box) => box.key), <String>[
'plan',
'build',
'ship',
failureEnd,
successEnd,
]);
expect(layout.ranks, <String, int>{
'plan': 0,
'build': 1,
'ship': 2,
failureEnd: 3,
successEnd: 3,
});
expect(layout.nodeFor('plan')!.stageIndex, 0);
expect(layout.nodeFor('build')!.stageIndex, 1);
expect(layout.nodeFor('ship')!.stageIndex, 2);
expect(layout.nodeFor(failureEnd)!.terminal, isTrue);
expect(layout.nodeFor(failureEnd)!.stageIndex, isNull);
expect(layout.nodeFor(successEnd)!.terminal, isTrue);
expect(
layout.nodeFor(successEnd)!.y - layout.nodeFor(failureEnd)!.bottom,
layoutConfig().rowGap,
);
expect(layout.nodeFor(failureEnd)!.x, layout.nodeFor(successEnd)!.x);
expect(layout.nodeFor('plan')!.x, layoutConfig().padding);
expect(layout.nodeFor('plan')!.y, layoutConfig().padding);
expect(
layout.nodeFor('build')!.x - layout.nodeFor('plan')!.right,
layoutConfig().columnGap,
);
expect(layout.width, 560);
expect(layout.height, 140);
_expectWithinBounds(layout);
_expectSeparated(layout);
});
test('diamond ranks place siblings in one column', () {
final layout = _layout(diamondGraphFixture());
final b = layout.nodeFor('b')!;
final c = layout.nodeFor('c')!;
expect(b.rank, 1);
expect(c.rank, 1);
expect(b.x, c.x);
expect(c.y - b.bottom, layoutConfig().rowGap);
expect(layout.nodeFor('d')!.rank, 2);
expect(layout.nodeFor('d')!.x, greaterThan(b.right));
_expectWithinBounds(layout);
_expectSeparated(layout);
});
test('cycles share a column and terminals still follow them', () {
final layout = _layout(cycleGraph());
final a = layout.nodeFor('a')!;
final b = layout.nodeFor('b')!;
expect(a.rank, 0);
expect(b.rank, 0);
expect(b.y - a.bottom, layoutConfig().rowGap);
expect(layout.nodeFor(failureEnd)!.rank, 1);
expect(layout.nodeFor(successEnd)!.rank, 1);
_expectWithinBounds(layout);
_expectSeparated(layout);
});
test('self loops and disconnected stages stay finite and separate', () {
final selfLoop = _layout(selfLoopGraphFixture());
expect(selfLoop.nodeFor('a')!.rank, 0);
expect(selfLoop.nodeFor('b')!.rank, 1);
final disconnected = _layout(disconnectedGraph());
expect(disconnected.nodeFor('a')!.rank, 0);
expect(disconnected.nodeFor('b')!.rank, 0);
expect(disconnected.nodeFor('c')!.rank, 0);
expect(
disconnected.nodeFor('b')!.y,
greaterThan(disconnected.nodeFor('a')!.bottom),
);
_expectWithinBounds(selfLoop);
_expectSeparated(selfLoop);
_expectWithinBounds(disconnected);
_expectSeparated(disconnected);
});
test('unknown edge targets add no node and no column', () {
final graph = incompleteGraphFixture();
final layout = _layout(graph);
expect(
layout.nodes.map((box) => box.key),
graphNodes(graph).map((node) => node.key),
);
expect(layout.nodeFor('ghost'), isNull);
expect(layout.ranks.containsKey('ghost'), isFalse);
_expectWithinBounds(layout);
_expectSeparated(layout);
});
test('heterogeneous measured widths stay inside their columns', () {
final layout = _layout(
diamondGraphFixture(),
extents: heterogeneousExtents(),
);
for (final entry in heterogeneousExtents().entries) {
final box = layout.nodeFor(entry.key)!;
expect(box.width, entry.value.width, reason: '${entry.key} width');
expect(box.height, entry.value.height, reason: '${entry.key} height');
}
final b = layout.nodeFor('b')!;
final c = layout.nodeFor('c')!;
expect(b.rank, c.rank);
expect(b.x + b.width / 2, c.x + c.width / 2);
expect(c.y - b.bottom, layoutConfig().rowGap);
expect(layout.width, greaterThan(0));
expect(layout.width, 770);
expect(layout.height, 236);
_expectWithinBounds(layout);
_expectSeparated(layout);
});
test('expanded text extents grow the canvas without overlap or clipping', () {
final base = _layout(
diamondGraphFixture(),
extents: heterogeneousExtents(),
);
final expandedExtents = scaledExtents(heterogeneousExtents(), 2.6);
final expanded = _layout(diamondGraphFixture(), extents: expandedExtents);
expect(expanded.width, greaterThan(base.width));
expect(expanded.height, greaterThan(base.height));
for (final entry in expandedExtents.entries) {
final box = expanded.nodeFor(entry.key)!;
expect(box.width, entry.value.width, reason: '${entry.key} width');
expect(box.height, entry.value.height, reason: '${entry.key} height');
}
_expectWithinBounds(expanded);
_expectSeparated(expanded);
});
test('the same input produces the same immutable layout', () {
final graph = diamondGraphFixture();
final nodes = graphNodes(graph);
final edges = graphEdges(graph);
final extents = uniformExtents(nodes, width: 133, height: 77);
final first = layoutGraphNodes(
nodes: nodes,
edges: edges,
extents: extents,
config: layoutConfig(),
);
final second = layoutGraphNodes(
nodes: nodes,
edges: edges,
extents: extents,
config: layoutConfig(),
);
expect(second.nodes, first.nodes);
expect(second.ranks, first.ranks);
expect(second.width, first.width);
expect(second.height, first.height);
expect(second.rankCount, first.rankCount);
expect(() => second.nodes.add(first.nodes.first), throwsUnsupportedError);
expect(() => second.ranks['a'] = 99, throwsUnsupportedError);
});
}
@@ -0,0 +1,116 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
import 'package:pipelines_app/features/graph/layout/graph_ranks.dart';
import 'layout_fixtures.dart';
GraphRanks _ranksFor(Map<String, dynamic> graph) {
return assignGraphRanks(graphNodes(graph), graphEdges(graph));
}
void main() {
test('linear definitions rank one stage per column', () {
final ranks = _ranksFor(linearGraphFixture());
expect(ranks.rankOf, <String, int>{
'plan': 0,
'build': 1,
'ship': 2,
failureEnd: 3,
successEnd: 3,
});
expect(ranks.rankCount, 4);
expect(ranks.components, <List<String>>[
<String>['plan'],
<String>['build'],
<String>['ship'],
<String>[failureEnd],
<String>[successEnd],
]);
});
test('diamond fan-out shares a rank and converges after it', () {
final ranks = _ranksFor(diamondGraphFixture());
expect(ranks.rankOf['a'], 0);
expect(ranks.rankOf['b'], ranks.rankOf['c']);
expect(ranks.rankOf['b'], 1);
expect(ranks.rankOf['d'], 2);
expect(ranks.rankOf[failureEnd], 1);
expect(ranks.rankOf[successEnd], 3);
expect(ranks.rankCount, 4);
});
test('a cycle collapses to one shared rank instead of recursing', () {
final ranks = _ranksFor(cycleGraph());
expect(ranks.rankOf['a'], 0);
expect(ranks.rankOf['b'], 0);
expect(ranks.rankOf[failureEnd], 1);
expect(ranks.rankOf[successEnd], 1);
expect(ranks.rankCount, 2);
expect(ranks.components, contains(equals(<String>['a', 'b'])));
});
test('a self edge stays inside its own component and adds no rank', () {
final ranks = _ranksFor(selfLoopGraphFixture());
expect(ranks.rankOf, <String, int>{
'a': 0,
'b': 1,
failureEnd: 2,
successEnd: 2,
});
expect(ranks.components, contains(equals(<String>['a'])));
expect(ranks.components, contains(equals(<String>['b'])));
});
test('disconnected stages stay at rank zero', () {
final ranks = _ranksFor(disconnectedGraph());
expect(ranks.rankOf['a'], 0);
expect(ranks.rankOf['b'], 0);
expect(ranks.rankOf['c'], 0);
expect(ranks.rankOf[failureEnd], 1);
expect(ranks.rankOf[successEnd], 1);
expect(ranks.rankCount, 2);
});
test('unknown and empty edge targets never become ranks or nodes', () {
final graph = incompleteGraphFixture();
final nodes = graphNodes(graph);
final ranks = assignGraphRanks(nodes, graphEdges(graph));
expect(nodes.map((node) => node.key), isNot(contains('ghost')));
expect(ranks.rankOf.containsKey('ghost'), isFalse);
expect(ranks.rankOf.containsKey(''), isFalse);
expect(ranks.rankOf['a'], 0);
expect(ranks.rankOf['b'], 0);
expect(ranks.rankOf[failureEnd], 1);
expect(ranks.rankOf[successEnd], 1);
});
test('ranks are stable across repeated assignments', () {
final graph = diamondGraphFixture();
final nodes = graphNodes(graph);
final edges = graphEdges(graph);
final first = assignGraphRanks(nodes, edges);
final second = assignGraphRanks(nodes, edges);
expect(second.rankOf, first.rankOf);
expect(second.rankCount, first.rankCount);
expect(second.components, first.components);
});
test('a long chain is walked iteratively without overflow', () {
const length = 2000;
final ranks = _ranksFor(chainGraph(length));
expect(ranks.rankCount, length + 1);
expect(ranks.rankOf['s0'], 0);
expect(ranks.rankOf['s${length - 1}'], length - 1);
expect(ranks.rankOf[successEnd], length);
});
}
@@ -0,0 +1,102 @@
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
import 'package:pipelines_app/features/graph/layout/layout_models.dart';
import '../domain/graph_fixtures.dart' as domain;
/// Small definitions and measured extents shared by the layout tests.
GraphLayoutConfig layoutConfig({
double columnGap = 24,
double rowGap = 12,
double padding = 4,
}) {
return GraphLayoutConfig(
columnGap: columnGap,
rowGap: rowGap,
padding: padding,
);
}
/// One measured size for every node, optionally scaled to simulate text growth.
Map<String, NodeExtent> uniformExtents(
Iterable<GraphNode> nodes, {
double width = 120,
double height = 60,
double scale = 1,
}) {
return <String, NodeExtent>{
for (final node in nodes)
node.key: NodeExtent(width: width * scale, height: height * scale),
};
}
Map<String, NodeExtent> scaledExtents(
Map<String, NodeExtent> base,
double scale,
) {
return <String, NodeExtent>{
for (final entry in base.entries)
entry.key: NodeExtent(
width: entry.value.width * scale,
height: entry.value.height * scale,
),
};
}
/// Deliberately uneven measured boxes for the diamond definition.
Map<String, NodeExtent> heterogeneousExtents() {
return <String, NodeExtent>{
'a': NodeExtent(width: 210, height: 84),
'b': NodeExtent(width: 92, height: 44),
'c': NodeExtent(width: 148, height: 126),
'd': NodeExtent(width: 104, height: 58),
failureEnd: NodeExtent(width: 72, height: 34),
successEnd: NodeExtent(width: 228, height: 96),
};
}
/// Two stages in a cycle; both terminals are reached from inside the cycle.
Map<String, dynamic> cycleGraph() => <String, dynamic>{
'stages': <dynamic>[
domain.stage(
'a',
edges: <String, String?>{'success': 'b', 'error': '#'},
fallbackError: true,
),
domain.stage(
'b',
edges: <String, String?>{'success': 'a', 'error': '#success'},
),
],
};
/// Two independent routes and a stage with no edges at all.
Map<String, dynamic> disconnectedGraph() => <String, dynamic>{
'stages': <dynamic>[
domain.stage('a', edges: <String, String?>{'success': '#success'}),
domain.stage('b', edges: <String, String?>{'success': '#failure'}),
domain.stage('c'),
],
};
Map<String, dynamic> linearGraphFixture() => domain.linearGraph();
Map<String, dynamic> diamondGraphFixture() => domain.diamondGraph();
Map<String, dynamic> selfLoopGraphFixture() => domain.selfLoopGraph();
Map<String, dynamic> incompleteGraphFixture() => domain.incompleteGraph();
/// A long chain, used to prove the iterative rank walk cannot overflow.
Map<String, dynamic> chainGraph(int length) => <String, dynamic>{
'stages': <dynamic>[
for (var index = 0; index < length; index += 1)
domain.stage(
's$index',
edges: <String, String?>{
'success': index + 1 < length ? 's${index + 1}' : '#success',
},
),
],
};
@@ -0,0 +1,41 @@
import 'package:flutter/material.dart';
import 'package:pipelines_app/features/graph/routing/route_models.dart';
/// Shared hand-built routes for the edge-layer painting tests.
EdgeRoute edgeRoute({
required List<RoutePoint> points,
RouteKind kind = RouteKind.forward,
RoutePortSide targetSide = RoutePortSide.left,
double portX = 0,
double portY = 0,
}) {
final start = points.isEmpty ? RoutePoint(portX, portY) : points.first;
final end = points.isEmpty ? RoutePoint(portX, portY) : points.last;
return EdgeRoute(
id: 1,
source: 'a',
outcome: 'success',
target: 'b',
label: 'success',
fallback: false,
kind: kind,
straight: false,
sourcePort: RoutePort(side: RoutePortSide.right, point: start),
targetPort: RoutePort(side: targetSide, point: end),
points: points,
);
}
Offset routeOffset(RoutePoint point) => Offset(point.x, point.y);
/// The direction of the route's last non-degenerate segment.
Offset arrival(EdgeRoute route) {
final points = route.points;
final end = points.last;
for (var index = points.length - 2; index >= 0; index -= 1) {
final delta = Offset(end.x - points[index].x, end.y - points[index].y);
if (delta != Offset.zero) return delta / delta.distance;
}
return Offset.zero;
}
@@ -0,0 +1,240 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/painting/graph_edge_layer.dart';
import 'package:pipelines_app/features/graph/routing/route_models.dart';
import '../routing/routing_fixtures.dart';
import 'edge_layer_fixtures.dart';
void main() {
const color = Colors.black87;
final straight = edgeRoute(
points: const [RoutePoint(10, 20), RoutePoint(90, 20)],
);
final wrapping = edgeRoute(
points: const [
RoutePoint(10, 20),
RoutePoint(40, 20),
RoutePoint(40, 60),
RoutePoint(80, 60),
RoutePoint(80, 50),
],
);
group('path', () {
test('keeps every orthogonal vertex of the supplied route', () {
final painter = GraphEdgePainter(
routes: [wrapping],
color: color,
strokeWidth: 2,
);
final path = painter.linePath(wrapping);
final metric = path.computeMetrics().single;
expect(metric.length, closeTo(30 + 40 + 40 + 10, 0.001));
expect(
metric.getTangentForOffset(0)!.position,
routeOffset(wrapping.points.first),
);
expect(
metric.getTangentForOffset(metric.length)!.position,
routeOffset(wrapping.points.last),
);
expect(path.getBounds(), const Rect.fromLTRB(10, 20, 80, 60));
});
test('a straight route is the exact port-to-port segment', () {
final painter = GraphEdgePainter(
routes: [straight],
color: color,
strokeWidth: 1,
);
final metric = painter.linePath(straight).computeMetrics().single;
expect(metric.length, 80);
expect(metric.getTangentForOffset(40)!.vector, const Offset(1, 0));
});
test('zero- and one-point routes produce an empty path', () {
final painter = GraphEdgePainter(
routes: const [],
color: color,
strokeWidth: 1,
);
final empty = edgeRoute(points: const []);
final single = edgeRoute(points: const [RoutePoint(5, 5)]);
for (final route in [empty, single]) {
final path = painter.linePath(route);
expect(path.getBounds().isEmpty, isTrue);
expect(path.computeMetrics().isEmpty, isTrue);
}
});
});
group('arrow', () {
test('points into a forward target port', () {
final painter = GraphEdgePainter(
routes: [straight],
color: color,
strokeWidth: 2,
);
final arrow = painter.arrowPath(straight);
final tip = routeOffset(straight.points.last);
expect(
arrow.computeMetrics().first.getTangentForOffset(0)!.position,
tip,
);
// 12 long and 8 wide for a 2px stroke, pointing right.
expect(arrow.getBounds(), const Rect.fromLTRB(78, 16, 90, 24));
expect(arrow.contains(tip.translate(-5, 0)), isTrue);
expect(arrow.contains(tip.translate(2, 0)), isFalse);
expect(arrow.contains(tip.translate(-14, 0)), isFalse);
});
test('follows self-loop arrival instead of assuming a rightward edge', () {
final routing = routeFor(selfLoopGraphFixture());
final loop = routing.routes.singleWhere(
(route) => route.kind == RouteKind.selfLoop,
);
final painter = GraphEdgePainter(
routes: routing.routes,
color: color,
strokeWidth: 2,
);
final direction = arrival(loop);
final tip = routeOffset(loop.points.last);
final arrow = painter.arrowPath(loop);
expect(loop.targetPort.side, RoutePortSide.right);
expect(direction.dx, -1);
expect(arrow.getBounds().left, tip.dx);
expect(arrow.contains(tip.translate(5, 0)), isTrue);
expect(arrow.contains(tip.translate(-2, 0)), isFalse);
});
test('a backward route keeps its leftward arrival into a right port', () {
final back = edgeRoute(
kind: RouteKind.back,
targetSide: RoutePortSide.right,
points: const [
RoutePoint(120, 20),
RoutePoint(140, 20),
RoutePoint(140, 60),
RoutePoint(80, 60),
],
);
final painter = GraphEdgePainter(
routes: [back],
color: color,
strokeWidth: 2,
);
final arrow = painter.arrowPath(back);
final tip = routeOffset(back.points.last);
expect(back.kind, RouteKind.back);
expect(arrow.getBounds().left, tip.dx);
expect(arrow.contains(tip.translate(5, 0)), isTrue);
expect(arrow.contains(tip.translate(-2, 0)), isFalse);
});
test('keeps the routed arrival direction for every cycle edge', () {
final routing = routeFor(cycleGraphFixture());
final painter = GraphEdgePainter(
routes: routing.routes,
color: color,
strokeWidth: 2,
);
expect(routing.routes, isNotEmpty);
for (final route in routing.routes) {
final direction = arrival(route);
final tip = routeOffset(route.points.last);
final arrow = painter.arrowPath(route);
expect(
arrow.computeMetrics().first.getTangentForOffset(0)!.position,
tip,
);
expect(arrow.contains(tip - direction * 5), isTrue);
expect(arrow.contains(tip + direction * 2), isFalse);
}
});
test('a routed forward edge ends exactly at its target port', () {
final routing = routeFor(chainGraphFixture());
final painter = GraphEdgePainter(
routes: routing.routes,
color: color,
strokeWidth: 2,
);
expect(routing.routes, isNotEmpty);
for (final route in routing.routes) {
expect(route.points.last, route.targetPort.point);
final arrow = painter.arrowPath(route);
expect(
arrow.computeMetrics().first.getTangentForOffset(0)!.position,
routeOffset(route.targetPort.point),
);
}
});
test('anchors the tip at the target port, not the last route point', () {
final route = EdgeRoute(
id: 7,
source: 'a',
outcome: 'success',
target: 'b',
label: 'success',
fallback: false,
kind: RouteKind.forward,
straight: true,
sourcePort: const RoutePort(
side: RoutePortSide.right,
point: RoutePoint(10, 20),
),
targetPort: const RoutePort(
side: RoutePortSide.left,
point: RoutePoint(85, 20),
),
points: const [RoutePoint(10, 20), RoutePoint(80, 20)],
);
final arrow = GraphEdgePainter(
routes: [route],
color: color,
strokeWidth: 2,
).arrowPath(route);
expect(
arrow.computeMetrics().first.getTangentForOffset(0)!.position,
const Offset(85, 20),
);
});
test('scales with the caller stroke width', () {
final small = GraphEdgePainter(
routes: [straight],
color: color,
strokeWidth: 1,
).arrowPath(straight);
final large = GraphEdgePainter(
routes: [straight],
color: color,
strokeWidth: 4,
).arrowPath(straight);
expect(small.getBounds().width, 6);
expect(small.getBounds().height, 4);
expect(large.getBounds().width, 24);
expect(large.getBounds().height, 16);
});
test('falls back to the port inward normal for a degenerate tail', () {
final route = edgeRoute(
points: const [RoutePoint(50, 50), RoutePoint(50, 50)],
targetSide: RoutePortSide.top,
);
final arrow = GraphEdgePainter(
routes: [route],
color: color,
strokeWidth: 2,
).arrowPath(route);
final tip = routeOffset(route.points.last);
expect(arrow.getBounds(), const Rect.fromLTRB(46, 38, 54, 50));
expect(arrow.contains(tip.translate(0, -5)), isTrue);
});
});
}
@@ -0,0 +1,190 @@
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/painting/graph_edge_layer.dart';
import 'package:pipelines_app/features/graph/routing/route_models.dart';
import 'edge_layer_fixtures.dart';
void main() {
const color = Colors.black87;
final straight = edgeRoute(
points: const [RoutePoint(10, 20), RoutePoint(90, 20)],
);
final wrapping = edgeRoute(
points: const [
RoutePoint(10, 20),
RoutePoint(40, 20),
RoutePoint(40, 60),
RoutePoint(80, 60),
RoutePoint(80, 50),
],
);
test('draws one stroke and one filled arrow per route, clipped', () {
final canvas = TestRecordingCanvas();
GraphEdgePainter(
routes: [straight, wrapping],
color: color,
strokeWidth: 2,
).paint(canvas, const Size(120, 80));
final calls = canvas.invocations
.where((call) => call.invocation.memberName == #drawPath)
.toList();
expect(calls.length, 4);
final paints = [
for (final call in calls)
call.invocation.positionalArguments.last as Paint,
];
expect(paints[0].style, PaintingStyle.stroke);
expect(paints[1].style, PaintingStyle.stroke);
expect(paints[2].style, PaintingStyle.fill);
expect(paints[3].style, PaintingStyle.fill);
expect(
paints.every((paint) => paint.color.toARGB32() == color.toARGB32()),
isTrue,
);
final clip = canvas.invocations.singleWhere(
(call) => call.invocation.memberName == #clipRect,
);
expect(
clip.invocation.positionalArguments.first,
const Rect.fromLTWH(0, 0, 120, 80),
);
});
test('paints nothing for an empty route list', () {
final canvas = TestRecordingCanvas();
GraphEdgePainter(
routes: const [],
color: color,
strokeWidth: 2,
).paint(canvas, const Size(120, 80));
expect(canvas.invocations, isEmpty);
});
test('reports every canvas point as a miss', () {
final painter = GraphEdgePainter(
routes: [straight],
color: color,
strokeWidth: 2,
);
expect(painter.hitTest(const Offset(50, 20)), isFalse);
expect(painter.hitTest(const Offset(500, 500)), isFalse);
});
testWidgets('clips painted geometry to the canvas bounds', (tester) async {
final recorder = ui.PictureRecorder();
GraphEdgePainter(
routes: [
edgeRoute(points: const [RoutePoint(-30, 10), RoutePoint(60, 10)]),
],
color: Colors.black,
strokeWidth: 6,
).paint(Canvas(recorder), const Size(20, 20));
final data = await tester.runAsync(() async {
final image = await recorder.endRecording().toImage(80, 40);
final bytes = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
image.dispose();
return bytes;
});
expect(data, isNotNull);
final bytes = data!.buffer.asUint8List();
int alphaAt(int x, int y) => bytes[(y * 80 + x) * 4 + 3];
expect(alphaAt(10, 10), 255, reason: 'inside the clip is painted');
expect(alphaAt(40, 10), 0, reason: 'the route continues past the clip');
expect(alphaAt(10, 35), 0, reason: 'below the canvas stays empty');
});
testWidgets('lets taps through to a sibling below the canvas', (
tester,
) async {
var taps = 0;
Widget harness(List<EdgeRoute> routes) => MaterialApp(
home: Center(
child: SizedBox(
width: 200,
height: 100,
child: Stack(
children: [
Positioned.fill(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => taps += 1,
),
),
GraphEdgeLayer(
routes: routes,
canvasSize: const Size(200, 100),
color: color,
strokeWidth: 2,
),
],
),
),
),
);
for (final routes in <List<EdgeRoute>>[
const <EdgeRoute>[],
[straight],
]) {
await tester.pumpWidget(harness(routes));
final origin = tester.getTopLeft(find.byType(GraphEdgeLayer));
final before = taps;
await tester.tapAt(origin + const Offset(50, 20));
await tester.tapAt(origin + const Offset(150, 80));
expect(taps, before + 2, reason: 'routes=$routes');
}
});
test('repaints on route, color or stroke changes only', () {
final painter = GraphEdgePainter(
routes: [straight],
color: color,
strokeWidth: 2,
);
GraphEdgePainter copy({
List<EdgeRoute>? routes,
Color? color,
double? strokeWidth,
}) => GraphEdgePainter(
routes: routes ?? [straight],
color: color ?? Colors.black87,
strokeWidth: strokeWidth ?? 2,
);
expect(painter.shouldRepaint(copy()), isFalse);
expect(painter.shouldRepaint(copy(color: Colors.red)), isTrue);
expect(painter.shouldRepaint(copy(strokeWidth: 3)), isTrue);
expect(
painter.shouldRepaint(
copy(
routes: [
edgeRoute(points: const [RoutePoint(10, 20), RoutePoint(90, 30)]),
],
),
),
isTrue,
);
});
testWidgets('lays out at the supplied canvas size', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Center(
child: GraphEdgeLayer(
routes: [wrapping],
canvasSize: const Size(120, 80),
color: color,
strokeWidth: 2,
),
),
),
);
expect(tester.getSize(find.byType(GraphEdgeLayer)), const Size(120, 80));
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,191 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
import 'package:pipelines_app/features/graph/routing/route_models.dart';
import '../layout/layout_fixtures.dart' as layout;
import 'routing_assertions.dart';
import 'routing_fixtures.dart';
void main() {
test('chain routes keep identities and use straight forward runs', () {
final graph = chainGraphFixture();
final layoutBox = layoutFor(graph);
final edges = graphEdges(graph);
final labels = labelsFor(edges);
final routing = routeFor(graph, labels: labels);
expect(routing.skipped, isEmpty);
expect(
routing.routes.map((route) => route.id),
edges.map((edge) => edge.id),
);
for (var index = 0; index < edges.length; index += 1) {
final edge = edges[index];
final route = routing.routes[index];
expect(route.source, edge.source);
expect(route.outcome, edge.outcome);
expect(route.target, edge.target);
expect(route.label, edge.label);
expect(route.fallback, edge.fallback);
expect(route.kind, RouteKind.forward);
expect(route.straight, isTrue);
expect(route.points.length, 2);
expect(route.sourcePort.side, RoutePortSide.right);
expect(route.targetPort.side, RoutePortSide.left);
}
expectValidRouting(routing, layoutBox, extents: labels);
});
test('diamond fan-out and fan-in avoid every node interior', () {
final graph = diamondGraphFixture();
final layoutBox = layoutFor(graph);
final labels = labelsFor(graphEdges(graph));
final routing = routeFor(graph, labels: labels);
expect(routing.skipped, isEmpty);
expect(routing.routes.length, graphEdges(graph).length);
final fromA = routing.routes.where((route) => route.source == 'a');
expect(fromA.length, 3);
expect(
fromA.where((route) => route.straight).length,
greaterThanOrEqualTo(1),
);
final longForward = fromA.singleWhere(
(route) => route.target == failureEnd,
);
expect(longForward.kind, RouteKind.forward);
expect(longForward.straight, isFalse);
expect(longForward.points.length, greaterThan(4));
expectValidRouting(routing, layoutBox, extents: labels);
});
test('parallel outcomes to one target get separate corridors and labels', () {
final graph = parallelOutcomesGraph();
final layoutBox = layoutFor(graph);
final labels = labelsFor(graphEdges(graph));
final routing = routeFor(graph, labels: labels);
final parallel = routing.routes
.where((route) => route.source == 'a' && route.target == 'b')
.toList();
expect(parallel.length, 3);
final ports = <String>{
for (final route in parallel)
'${route.sourcePort.point.y}/${route.targetPort.point.y}',
};
expect(ports.length, 3, reason: 'each outcome has its own port pair');
final labelBoxes = <EdgeLabelBox>[
for (final route in parallel) routing.labelFor(route.id)!,
];
expect(labelBoxes.map((box) => box.y).toSet().length, greaterThan(1));
expectValidRouting(routing, layoutBox, extents: labels);
});
test('a same-rank cycle uses distinct lanes around both members', () {
final graph = cycleGraphFixture();
final layoutBox = layoutFor(graph);
final labels = labelsFor(graphEdges(graph));
final routing = routeFor(graph, labels: labels);
final sameRank = routing.routes
.where((route) => route.kind == RouteKind.sameRank)
.toList();
expect(sameRank.length, 2);
expect(sameRank.map((route) => route.target).toSet(), <String>{'a', 'b'});
for (final route in sameRank) {
expect(route.straight, isFalse);
expect(route.sourcePort.side, RoutePortSide.right);
expect(route.targetPort.side, RoutePortSide.right);
expect(
route.points.map((point) => point.y).toSet().length,
greaterThan(2),
);
}
expectValidRouting(routing, layoutBox, extents: labels);
});
test('a self loop expands bounds and keeps both ports on its border', () {
final graph = selfLoopOnlyGraph();
final layoutBox = layoutFor(graph);
final labels = labelsFor(graphEdges(graph));
final routing = routeFor(graph, labels: labels);
final route = routing.routes.single;
expect(route.kind, RouteKind.selfLoop);
expect(route.straight, isFalse);
expect(route.points.length, greaterThanOrEqualTo(4));
expect(route.sourcePort.side, RoutePortSide.right);
expect(route.targetPort.side, RoutePortSide.right);
expect(route.sourcePort.point.y, isNot(route.targetPort.point.y));
expect(routing.width, greaterThan(layoutBox.width));
expect(routing.height, greaterThan(layoutBox.height));
expectValidRouting(routing, layoutBox, extents: labels);
});
test('disconnected stages route only their declared edges', () {
final graph = disconnectedGraphFixture();
final layoutBox = layoutFor(graph);
final labels = labelsFor(graphEdges(graph));
final routing = routeFor(graph, labels: labels);
expect(routing.skipped, isEmpty);
expect(routing.routes.length, 2);
expect(routing.routes.map((route) => route.source).toSet(), <String>{
'a',
'b',
});
expect(layoutBox.nodeFor('c'), isNotNull);
expect(routing.routes.any((route) => route.source == 'c'), isFalse);
expectValidRouting(routing, layoutBox, extents: labels);
});
test('heterogeneous and expanded text sizes stay valid and grow bounds', () {
final graph = diamondGraphFixture();
final baseLayout = layoutFor(graph, extents: layout.heterogeneousExtents());
final expandedExtents = layout.scaledExtents(
layout.heterogeneousExtents(),
2.6,
);
final expandedLayout = layoutFor(graph, extents: expandedExtents);
final edges = graphEdges(graph);
final labels = fixedLabels(edges);
final base = routeFor(
graph,
extents: layout.heterogeneousExtents(),
labels: labels,
);
final expanded = routeFor(graph, extents: expandedExtents, labels: labels);
expectValidRouting(base, baseLayout, extents: labels);
expectValidRouting(expanded, expandedLayout, extents: labels);
expect(expanded.width, greaterThan(base.width));
expect(expanded.height, greaterThan(base.height));
});
test('unknown and missing targets are skipped with their identity', () {
final graph = incompleteGraphFixture();
final layoutBox = layoutFor(graph);
final edges = graphEdges(graph);
final labels = labelsFor(edges);
final routing = routeFor(graph, labels: labels);
expect(routing.skipped.length, 2);
final skipped = routing.skipped.toList();
expect(skipped.map((item) => item.reason), <RouteSkipReason>[
RouteSkipReason.unknownTarget,
RouteSkipReason.unknownTarget,
]);
expect(skipped.map((item) => item.id), <int>[1, 2]);
expect(skipped[0].source, 'a');
expect(skipped[0].outcome, 'blocked');
expect(skipped[0].target, '');
expect(skipped[1].target, 'ghost');
expect(routing.routes.map((route) => route.id), <int>[3, 4]);
expect(routing.routeFor(1), isNull);
expect(routing.routeFor(2), isNull);
expect(layoutBox.nodeFor('ghost'), isNull);
expectValidRouting(routing, layoutBox, extents: labels);
});
}
@@ -0,0 +1,161 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
import 'package:pipelines_app/features/graph/layout/layout_models.dart';
import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart';
import 'package:pipelines_app/features/graph/routing/route_models.dart';
import 'routing_assertions.dart';
import 'routing_fixtures.dart';
import '../layout/layout_fixtures.dart' as layout;
void main() {
test(
'wide measured labels move outside the drawing instead of covering it',
() {
final graph = chainGraphFixture();
final layoutBox = layoutFor(graph);
final edges = graphEdges(graph);
final labels = fixedLabels(edges, width: 400, height: 40);
final routing = routeFor(graph, labels: labels);
expect(routing.labels.length, edges.length);
for (final label in routing.labels) {
expect(label.y, greaterThanOrEqualTo(layoutBox.height));
expect(label.right, lessThanOrEqualTo(routing.width));
expect(label.bottom, lessThanOrEqualTo(routing.height));
}
expect(routing.height, greaterThan(layoutBox.height));
expectValidRouting(routing, layoutBox, extents: labels);
},
);
test('tight gaps and expanded extents keep the same guarantees', () {
for (final gap in <double>[8, 24, 80]) {
for (final scale in <double>[1, 2.6]) {
final extents = layout.scaledExtents(
layout.heterogeneousExtents(),
scale,
);
final layoutBox = layoutFor(
diamondGraphFixture(),
extents: extents,
config: routingLayoutConfig(columnGap: gap, rowGap: 16),
);
final edges = graphEdges(diamondGraphFixture());
final labels = labelsFor(edges);
final routing = routeFor(
diamondGraphFixture(),
extents: extents,
labels: labels,
layoutConfig: routingLayoutConfig(columnGap: gap, rowGap: 16),
);
expectValidRouting(routing, layoutBox, extents: labels);
}
}
});
test('a three-stage cycle keeps every same-rank corridor distinct', () {
final graph = cycleThreeGraph();
final layoutBox = layoutFor(
graph,
config: routingLayoutConfig(columnGap: 8),
);
final edges = graphEdges(graph);
final labels = labelsFor(edges);
final routing = routeFor(
graph,
labels: labels,
layoutConfig: routingLayoutConfig(columnGap: 8),
);
expect(routing.routes.length, 3);
expect(
routing.routes.every((route) => route.kind == RouteKind.sameRank),
isTrue,
);
expectValidRouting(routing, layoutBox, extents: labels);
});
test('a caller-supplied backward rank routes around the target column', () {
final layoutBox = GraphLayout(
nodes: <GraphNodeBox>[
const GraphNodeBox(
key: 'a',
terminal: false,
stageIndex: 0,
rank: 1,
x: 208,
y: 8,
width: 120,
height: 60,
),
const GraphNodeBox(
key: 'b',
terminal: false,
stageIndex: 1,
rank: 0,
x: 8,
y: 8,
width: 120,
height: 60,
),
],
ranks: <String, int>{'a': 1, 'b': 0},
rankCount: 2,
width: 336,
height: 76,
);
final edge = GraphEdge(
id: 1,
source: 'a',
outcome: 'success',
target: 'b',
label: 'success',
fallback: false,
knownTarget: true,
);
final labels = <int, LabelExtent>{1: LabelExtent(width: 52, height: 18)};
final routing = routeGraphEdges(
layout: layoutBox,
edges: <GraphEdge>[edge],
labelExtents: labels,
config: routingConfig(),
);
final route = routing.routes.single;
expect(route.kind, RouteKind.back);
expect(route.sourcePort.side, RoutePortSide.right);
expect(route.targetPort.side, RoutePortSide.right);
expect(route.straight, isFalse);
expect(route.points.length, greaterThan(4));
expect(routing.width, greaterThan(layoutBox.width));
expectValidRouting(routing, layoutBox, extents: labels);
});
test('a self loop and forward routes share one valid layout', () {
final graph = selfLoopGraphFixture();
final layoutBox = layoutFor(graph);
final labels = labelsFor(graphEdges(graph));
final routing = routeFor(graph, labels: labels);
expect(routing.routes.length, 4);
expect(routing.routes.map((route) => route.kind).toSet(), <RouteKind>{
RouteKind.forward,
RouteKind.selfLoop,
});
final loop = routing.routes.singleWhere(
(route) => route.kind == RouteKind.selfLoop,
);
expect(loop.source, 'a');
expect(loop.target, 'a');
expect(loop.sourcePort.point.y, isNot(loop.targetPort.point.y));
expect(
routing.routes
.where((route) => route.target == successEnd)
.every((route) => route.targetPort.side == RoutePortSide.left),
isTrue,
);
expectValidRouting(routing, layoutBox, extents: labels);
});
}
@@ -0,0 +1,222 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart';
import 'package:pipelines_app/features/graph/routing/route_models.dart';
import 'routing_fixtures.dart';
GraphEdge _edge({
int id = 1,
String source = 'a',
String target = 'b',
String outcome = 'success',
bool knownTarget = true,
}) {
return GraphEdge(
id: id,
source: source,
outcome: outcome,
target: target,
label: outcome,
fallback: false,
knownTarget: knownTarget,
);
}
void main() {
test('an empty graph has empty routes and the layout bounds', () {
final layoutBox = layoutFor(<String, dynamic>{'stages': <dynamic>[]});
final routing = routeGraphEdges(
layout: layoutBox,
edges: const <GraphEdge>[],
labelExtents: const <int, LabelExtent>{},
config: routingConfig(),
);
expect(routing.isEmpty, isTrue);
expect(routing.routes, isEmpty);
expect(routing.labels, isEmpty);
expect(routing.skipped, isEmpty);
expect(routing.width, layoutBox.width + routingConfig().boundsPadding);
expect(routing.height, layoutBox.height + routingConfig().boundsPadding);
});
test('unknown endpoints become diagnostics, never invented nodes', () {
final layoutBox = layoutFor(chainGraphFixture());
final edges = <GraphEdge>[
_edge(id: 1, source: 'missing', target: 's0'),
_edge(id: 2, source: 's0', target: 'ghost'),
_edge(id: 3, source: 's0', target: '', knownTarget: false),
];
final routing = routeGraphEdges(
layout: layoutBox,
edges: edges,
labelExtents: const <int, LabelExtent>{},
config: routingConfig(),
);
expect(routing.routes, isEmpty);
expect(routing.skipped.map((item) => item.reason), <RouteSkipReason>[
RouteSkipReason.unknownSource,
RouteSkipReason.unknownTarget,
RouteSkipReason.unknownTarget,
]);
expect(routing.skipped.map((item) => item.id), <int>[1, 2, 3]);
expect(layoutBox.nodeFor('missing'), isNull);
expect(layoutBox.nodeFor('ghost'), isNull);
});
test('routed edges require measured label extents', () {
final graph = diamondGraphFixture();
final layoutBox = layoutFor(graph);
final edges = graphEdges(graph);
final labels = labelsFor(edges)..remove(edges.first.id);
expect(
() => routeGraphEdges(
layout: layoutBox,
edges: edges,
labelExtents: labels,
config: routingConfig(),
),
throwsArgumentError,
);
});
test('extra label extents are ignored and duplicate ids are rejected', () {
final graph = diamondGraphFixture();
final layoutBox = layoutFor(graph);
final edges = graphEdges(graph);
final labels = labelsFor(edges)..[999] = LabelExtent(width: 10, height: 10);
final routing = routeGraphEdges(
layout: layoutBox,
edges: edges,
labelExtents: labels,
config: routingConfig(),
);
expect(routing.routes.length, edges.length);
expect(routing.labelFor(999), isNull);
expect(
() => routeGraphEdges(
layout: layoutBox,
edges: <GraphEdge>[edges.first, edges.first],
labelExtents: labelsFor(edges),
config: routingConfig(),
),
throwsArgumentError,
);
});
test('invalid configuration and label extents are rejected', () {
expect(
() => RoutingConfig(
nodeClearance: -1,
laneSpacing: 10,
corridorSpacing: 10,
portSpacing: 8,
labelGap: 2,
),
throwsArgumentError,
);
expect(
() => RoutingConfig(
nodeClearance: 2,
laneSpacing: 0,
corridorSpacing: 10,
portSpacing: 8,
labelGap: 2,
),
throwsArgumentError,
);
expect(
() => RoutingConfig(
nodeClearance: 2,
laneSpacing: 10,
corridorSpacing: double.nan,
portSpacing: 8,
labelGap: 2,
),
throwsArgumentError,
);
expect(
() => LabelExtent(width: double.infinity, height: 10),
throwsArgumentError,
);
expect(() => LabelExtent(width: 10, height: -1), throwsArgumentError);
});
test('the same input produces equal immutable results', () {
final graph = diamondGraphFixture();
final layoutBox = layoutFor(graph);
final edges = graphEdges(graph);
final labels = labelsFor(edges);
final config = routingConfig();
final first = routeGraphEdges(
layout: layoutBox,
edges: edges,
labelExtents: labels,
config: config,
);
final second = routeGraphEdges(
layout: layoutBox,
edges: edges,
labelExtents: labels,
config: config,
);
expect(first.routes, second.routes);
expect(first.labels, second.labels);
expect(first.skipped, second.skipped);
expect(first.width, second.width);
expect(first.height, second.height);
expect(() => first.routes.add(first.routes.first), throwsUnsupportedError);
expect(
() => first.routes.first.points.add(const RoutePoint(0, 0)),
throwsUnsupportedError,
);
expect(() => first.labels.add(first.labels.first), throwsUnsupportedError);
expect(
() => first.skipped.add(
const RouteDiagnostic(
id: 1,
source: 'a',
outcome: 'success',
target: 'b',
reason: RouteSkipReason.unknownTarget,
message: '',
),
),
throwsUnsupportedError,
);
});
test('edges are routed in definition id order regardless of input order', () {
final graph = diamondGraphFixture();
final layoutBox = layoutFor(graph);
final edges = graphEdges(graph);
final labels = labelsFor(edges);
final forward = routeGraphEdges(
layout: layoutBox,
edges: edges,
labelExtents: labels,
config: routingConfig(),
);
final reversed = routeGraphEdges(
layout: layoutBox,
edges: edges.reversed.toList(),
labelExtents: labels,
config: routingConfig(),
);
expect(reversed.routes, forward.routes);
expect(reversed.labels, forward.labels);
expect(reversed.width, forward.width);
expect(reversed.height, forward.height);
expect(
forward.routes.map((route) => route.id),
edges.map((edge) => edge.id),
);
});
}
@@ -0,0 +1,215 @@
import 'dart:math' as math;
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/layout/layout_models.dart';
import 'package:pipelines_app/features/graph/routing/route_models.dart';
const double _epsilon = 1e-9;
/// Checks the routing guarantees every fixture must satisfy.
void expectValidRouting(
GraphRouting routing,
GraphLayout layout, {
Map<int, LabelExtent>? extents,
}) {
expect(routing.width.isFinite, isTrue);
expect(routing.height.isFinite, isTrue);
expect(routing.width, greaterThan(0));
expect(routing.height, greaterThan(0));
for (final route in routing.routes) {
_expectRoute(route, layout, routing.width, routing.height);
_expectNoNodeInterior(route, layout);
}
expectDistinctCorridors(routing.routes);
final byId = <int, EdgeLabelBox>{
for (final label in routing.labels) label.edgeId: label,
};
expect(byId.length, routing.labels.length, reason: 'one label per edge');
for (final route in routing.routes) {
final label = byId[route.id];
expect(label, isNotNull, reason: 'edge ${route.id} has a label');
final extent = extents?[route.id];
if (extent != null) {
expect(label!.width, extent.width);
expect(label.height, extent.height);
}
expect(label!.x, greaterThanOrEqualTo(-_epsilon));
expect(label.y, greaterThanOrEqualTo(-_epsilon));
expect(label.right, lessThanOrEqualTo(routing.width + _epsilon));
expect(label.bottom, lessThanOrEqualTo(routing.height + _epsilon));
for (final node in layout.nodes) {
expect(
_overlaps(
label.x,
label.y,
label.width,
label.height,
node.x,
node.y,
node.width,
node.height,
),
isFalse,
reason: 'label for edge ${route.id} overlaps node ${node.key}',
);
}
}
for (var first = 0; first < routing.labels.length; first += 1) {
for (var second = first + 1; second < routing.labels.length; second += 1) {
final a = routing.labels[first];
final b = routing.labels[second];
expect(
_overlaps(a.x, a.y, a.width, a.height, b.x, b.y, b.width, b.height),
isFalse,
reason: 'labels for edges ${a.edgeId} and ${b.edgeId} overlap',
);
}
}
for (final skipped in routing.skipped) {
expect(routing.routeFor(skipped.id), isNull);
expect(routing.labelFor(skipped.id), isNull);
}
}
void expectDistinctCorridors(List<EdgeRoute> routes) {
for (var first = 0; first < routes.length; first += 1) {
for (var second = first + 1; second < routes.length; second += 1) {
final a = routes[first];
final b = routes[second];
for (var ai = 1; ai < a.points.length; ai += 1) {
final a0 = a.points[ai - 1];
final a1 = a.points[ai];
for (var bi = 1; bi < b.points.length; bi += 1) {
final b0 = b.points[bi - 1];
final b1 = b.points[bi];
if (a0.x == a1.x && b0.x == b1.x && a0.x == b0.x) {
final aLo = math.min(a0.y, a1.y);
final aHi = math.max(a0.y, a1.y);
final bLo = math.min(b0.y, b1.y);
final bHi = math.max(b0.y, b1.y);
expect(
aLo < bHi - _epsilon && bLo < aHi - _epsilon,
isFalse,
reason: 'edges ${a.id} and ${b.id} share a vertical corridor',
);
}
if (a0.y == a1.y && b0.y == b1.y && a0.y == b0.y) {
final aLo = math.min(a0.x, a1.x);
final aHi = math.max(a0.x, a1.x);
final bLo = math.min(b0.x, b1.x);
final bHi = math.max(b0.x, b1.x);
expect(
aLo < bHi - _epsilon && bLo < aHi - _epsilon,
isFalse,
reason: 'edges ${a.id} and ${b.id} share a horizontal run',
);
}
}
}
}
}
}
void _expectRoute(
EdgeRoute route,
GraphLayout layout,
double width,
double height,
) {
expect(route.points.length, greaterThanOrEqualTo(2));
expect(route.points.first, route.sourcePort.point);
expect(route.points.last, route.targetPort.point);
for (var index = 0; index < route.points.length; index += 1) {
final point = route.points[index];
expect(point.x.isFinite, isTrue);
expect(point.y.isFinite, isTrue);
expect(point.x, greaterThanOrEqualTo(-_epsilon));
expect(point.y, greaterThanOrEqualTo(-_epsilon));
expect(point.x, lessThanOrEqualTo(width + _epsilon));
expect(point.y, lessThanOrEqualTo(height + _epsilon));
if (index > 0) {
final previous = route.points[index - 1];
expect(
previous.x == point.x || previous.y == point.y,
isTrue,
reason: 'edge ${route.id} segment ${index - 1} is not orthogonal',
);
expect(previous, isNot(point), reason: 'zero-length segment');
}
}
_expectPort(route.sourcePort, layout.nodeFor(route.source)!);
_expectPort(route.targetPort, layout.nodeFor(route.target)!);
}
void _expectPort(RoutePort port, GraphNodeBox box) {
switch (port.side) {
case RoutePortSide.right:
expect(port.point.x, closeTo(box.right, _epsilon));
expect(port.point.y, greaterThanOrEqualTo(box.y - _epsilon));
expect(port.point.y, lessThanOrEqualTo(box.bottom + _epsilon));
case RoutePortSide.left:
expect(port.point.x, closeTo(box.x, _epsilon));
expect(port.point.y, greaterThanOrEqualTo(box.y - _epsilon));
expect(port.point.y, lessThanOrEqualTo(box.bottom + _epsilon));
case RoutePortSide.top:
expect(port.point.y, closeTo(box.y, _epsilon));
expect(port.point.x, greaterThanOrEqualTo(box.x - _epsilon));
expect(port.point.x, lessThanOrEqualTo(box.right + _epsilon));
case RoutePortSide.bottom:
expect(port.point.y, closeTo(box.bottom, _epsilon));
expect(port.point.x, greaterThanOrEqualTo(box.x - _epsilon));
expect(port.point.x, lessThanOrEqualTo(box.right + _epsilon));
}
}
void _expectNoNodeInterior(EdgeRoute route, GraphLayout layout) {
for (var index = 1; index < route.points.length; index += 1) {
final a = route.points[index - 1];
final b = route.points[index];
for (final node in layout.nodes) {
if (a.y == b.y) {
final left = math.min(a.x, b.x);
final right = math.max(a.x, b.x);
final crosses =
a.y > node.y + _epsilon &&
a.y < node.bottom - _epsilon &&
right > node.x + _epsilon &&
left < node.right - _epsilon;
expect(
crosses,
isFalse,
reason: 'edge ${route.id} crosses node ${node.key} horizontally',
);
} else {
final top = math.min(a.y, b.y);
final bottom = math.max(a.y, b.y);
final crosses =
a.x > node.x + _epsilon &&
a.x < node.right - _epsilon &&
bottom > node.y + _epsilon &&
top < node.bottom - _epsilon;
expect(
crosses,
isFalse,
reason: 'edge ${route.id} crosses node ${node.key} vertically',
);
}
}
}
}
bool _overlaps(
double ax,
double ay,
double aw,
double ah,
double bx,
double by,
double bw,
double bh,
) {
return ax < bx + bw && ax + aw > bx && ay < by + bh && ay + ah > by;
}
@@ -0,0 +1,143 @@
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart';
import 'package:pipelines_app/features/graph/layout/layout_models.dart';
import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart';
import 'package:pipelines_app/features/graph/routing/route_models.dart';
import '../layout/layout_fixtures.dart' as layout;
import '../domain/graph_fixtures.dart' as domain;
/// Definitions, measured extents and configs shared by the routing tests.
GraphLayoutConfig routingLayoutConfig({
double columnGap = 80,
double rowGap = 16,
double padding = 8,
}) {
return GraphLayoutConfig(
columnGap: columnGap,
rowGap: rowGap,
padding: padding,
);
}
RoutingConfig routingConfig({
double nodeClearance = 8,
double laneSpacing = 28,
double corridorSpacing = 20,
double portSpacing = 12,
double labelGap = 4,
double boundsPadding = 4,
}) {
return RoutingConfig(
nodeClearance: nodeClearance,
laneSpacing: laneSpacing,
corridorSpacing: corridorSpacing,
portSpacing: portSpacing,
labelGap: labelGap,
boundsPadding: boundsPadding,
);
}
GraphLayout layoutFor(
Map<String, dynamic> graph, {
Map<String, NodeExtent>? extents,
GraphLayoutConfig? config,
}) {
final nodes = graphNodes(graph);
return layoutGraphNodes(
nodes: nodes,
edges: graphEdges(graph),
extents: extents ?? layout.uniformExtents(nodes),
config: config ?? routingLayoutConfig(),
);
}
/// Measured label boxes sized from their text, as a renderer would supply them.
Map<int, LabelExtent> labelsFor(
Iterable<GraphEdge> edges, {
double charWidth = 7,
double padding = 12,
double height = 18,
}) {
return <int, LabelExtent>{
for (final edge in edges)
edge.id: LabelExtent(
width: edge.label.length * charWidth + padding,
height: height,
),
};
}
/// One box per edge at an explicit size, used for wide-label checks.
Map<int, LabelExtent> fixedLabels(
Iterable<GraphEdge> edges, {
double width = 52,
double height = 18,
}) {
return <int, LabelExtent>{
for (final edge in edges)
edge.id: LabelExtent(width: width, height: height),
};
}
GraphRouting routeFor(
Map<String, dynamic> graph, {
Map<String, NodeExtent>? extents,
Map<int, LabelExtent>? labels,
GraphLayoutConfig? layoutConfig,
RoutingConfig? config,
}) {
final layout = layoutFor(graph, extents: extents, config: layoutConfig);
final edges = graphEdges(graph);
return routeGraphEdges(
layout: layout,
edges: edges,
labelExtents: labels ?? labelsFor(edges),
config: config ?? routingConfig(),
);
}
/// Three outcomes from `a` to the same target `b`, then `b` to Success.
Map<String, dynamic> parallelOutcomesGraph() => <String, dynamic>{
'stages': <dynamic>[
domain.stage(
'a',
edges: <String, String?>{
'success': 'b',
'approved': 'b',
'rejected': 'b',
},
),
domain.stage('b', edges: <String, String?>{'success': '#success'}),
],
};
/// A single stage that retries itself and has no terminal pair.
Map<String, dynamic> selfLoopOnlyGraph() => <String, dynamic>{
'stages': <dynamic>[
domain.stage('a', edges: <String, String?>{'retry': 'a'}),
],
};
Map<String, dynamic> chainGraphFixture() => layout.chainGraph(4);
Map<String, dynamic> diamondGraphFixture() => layout.diamondGraphFixture();
Map<String, dynamic> cycleGraphFixture() => layout.cycleGraph();
Map<String, dynamic> selfLoopGraphFixture() => layout.selfLoopGraphFixture();
Map<String, dynamic> disconnectedGraphFixture() => layout.disconnectedGraph();
Map<String, dynamic> incompleteGraphFixture() =>
layout.incompleteGraphFixture();
/// Three stages in one strongly connected component with no terminals.
Map<String, dynamic> cycleThreeGraph() => <String, dynamic>{
'stages': <dynamic>[
domain.stage('a', edges: <String, String?>{'success': 'b'}),
domain.stage('b', edges: <String, String?>{'success': 'c'}),
domain.stage('c', edges: <String, String?>{'success': 'a'}),
],
};
@@ -0,0 +1,210 @@
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
const _stage = GraphNode(key: 'build', terminal: false, stageIndex: 1);
const _long = GraphNode(
key: 'implementer-with-an-unshortened-stage-label',
terminal: false,
stageIndex: 2,
);
const _longLabel = 'implementer-with-an-unshortened-stage-label';
Widget _material(Widget child) => MaterialApp(
home: Scaffold(body: Center(child: child)),
);
Widget _cupertino(Widget child) => CupertinoApp(
home: CupertinoPageScaffold(child: Center(child: child)),
);
/// The node centred on an opaque page, inside its own repaint boundary so the
/// painted result can be read back as pixels.
Widget _framed(Key key, Widget Function(Widget) wrap, Widget child) => wrap(
RepaintBoundary(
key: key,
child: ColoredBox(
color: const Color(0xFFFFFFFF),
child: Center(child: child),
),
),
);
Finder get _materialSurface =>
find.descendant(of: find.byType(Card), matching: find.byType(Material));
Finder _visual(String label) => find.byWidgetPredicate(
(widget) => widget is Text && widget.data?.replaceAll('\u200B', '') == label,
);
final class _Shot {
_Shot(this.bytes, this.size, this.origin);
final Uint8List bytes;
final Size size;
final Offset origin;
Color at(Offset global) {
final x = (global.dx - origin.dx).round();
final y = (global.dy - origin.dy).round();
expect(x, inInclusiveRange(0, size.width.round() - 1));
expect(y, inInclusiveRange(0, size.height.round() - 1));
final i = (y * size.width.round() + x) * 4;
return Color.fromARGB(bytes[i + 3], bytes[i], bytes[i + 1], bytes[i + 2]);
}
}
Future<_Shot> _shot(WidgetTester tester, Key key) async {
final boundary = tester.renderObject<RenderRepaintBoundary>(find.byKey(key));
final image = (await tester.runAsync(() => boundary.toImage()))!;
final data = (await tester.runAsync(
() => image.toByteData(format: ui.ImageByteFormat.rawRgba),
))!;
image.dispose();
return _Shot(
data.buffer.asUint8List(),
tester.getSize(find.byKey(key)),
tester.getTopLeft(find.byKey(key)),
);
}
double _distance(Color a, Color b) => <double>[
(a.r - b.r).abs() * 255,
(a.g - b.g).abs() * 255,
(a.b - b.b).abs() * 255,
].reduce((value, next) => value > next ? value : next);
void main() {
testWidgets('material node paints a rounded surface, not a stadium', (
tester,
) async {
await tester.pumpWidget(
_material(GraphStageNode(node: _stage, onSelected: (_) {})),
);
final material = tester.widget<Material>(_materialSurface);
expect(
material.shape,
isA<RoundedRectangleBorder>(),
reason:
'Material button shapes are stadiums; a stadium border cuts into a '
'wrapped label the way the reviewed 2x control did',
);
});
testWidgets('wrapped glyph boxes stay inside the painted material surface', (
tester,
) async {
for (final scale in [1.0, 2.0]) {
await tester.pumpWidget(
_material(
Builder(
builder: (context) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(scale)),
child: SizedBox(
width: 150,
child: GraphStageNode(node: _long, onSelected: (_) {}),
),
),
),
),
);
expect(tester.takeException(), isNull);
final rect = tester.getRect(_materialSurface);
final shape = tester.widget<Material>(_materialSurface).shape!;
final path = shape.getOuterPath(Offset.zero & rect.size);
final paragraph = tester.renderObject<RenderParagraph>(
_visual(_longLabel),
);
final boxes = paragraph.getBoxesForSelection(
TextSelection(
baseOffset: 0,
extentOffset: paragraph.text.toPlainText().length,
),
);
expect(boxes, isNotEmpty);
for (final box in boxes) {
final corners = <Offset>[
Offset(box.left, box.top),
Offset(box.right, box.top),
Offset(box.left, box.bottom),
Offset(box.right, box.bottom),
];
for (final corner in corners) {
final local = paragraph.localToGlobal(corner) - rect.topLeft;
expect(
path.contains(local),
isTrue,
reason:
'at ${scale}x a glyph box corner at $local escapes the '
'painted control boundary $rect',
);
}
}
}
});
testWidgets('unselected cupertino node paints a visible container', (
tester,
) async {
final key = GlobalKey();
await tester.pumpWidget(
_framed(
key,
_cupertino,
GraphStageNode(node: _stage, onSelected: (_) {}),
),
);
final shot = await _shot(tester, key);
final rect = tester.getRect(find.byType(CupertinoButton));
// Just inside the left edge of the control, clear of the label's inset.
final body = shot.at(rect.centerLeft + const Offset(4, 0));
final page = shot.at(const Offset(4, 4));
expect(
_distance(body, page),
greaterThan(24),
reason: 'an unselected cupertino node needs its own visible surface',
);
});
testWidgets('selected state changes the painted surface in both hosts', (
tester,
) async {
for (final wrap in [_material, _cupertino]) {
final colors = <bool, Color>{};
for (final selected in [false, true]) {
final key = GlobalKey();
await tester.pumpWidget(
_framed(
key,
wrap,
GraphStageNode(
node: _stage,
selected: selected,
onSelected: (_) {},
),
),
);
final shot = await _shot(tester, key);
final rect = tester.getRect(find.byType(GraphStageNode));
colors[selected] = shot.at(rect.centerLeft + const Offset(4, 0));
}
expect(
_distance(colors[false]!, colors[true]!),
greaterThan(16),
reason:
'selection must be visible, not only announced: the surface fill '
'and the outlined border change together',
);
}
});
}
@@ -0,0 +1,235 @@
import 'dart:ui' show Tristate;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
const _stage = GraphNode(key: 'build', terminal: false, stageIndex: 1);
const _success = GraphNode(key: '#success', terminal: true);
const _failure = GraphNode(key: '#failure', terminal: true);
Widget _material(Widget child) => MaterialApp(
home: Scaffold(body: Center(child: child)),
);
Widget _cupertino(Widget child) => CupertinoApp(
home: CupertinoPageScaffold(child: Center(child: child)),
);
/// Applies a 2x text scale below the app so the fixture renders as a real
/// scale-2 layout rather than a test-only text property.
Widget _scaled(Widget child) => Builder(
builder: (context) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: const TextScaler.linear(2)),
child: child,
),
);
/// The merged accessibility node a screen reader receives for one node.
SemanticsData _semantics(WidgetTester tester) =>
tester.getSemantics(find.byType(MergeSemantics)).getSemanticsData();
void _expectSelectable(WidgetTester tester, {required bool selected}) {
final data = _semantics(tester);
expect(data.flagsCollection.isButton, isTrue);
expect(data.flagsCollection.isSelected == Tristate.isTrue, selected);
expect(data.actions & SemanticsAction.tap.index, isNot(0));
}
/// Finds the visual line for [label], ignoring its invisible break chars.
Finder _visual(String label) => find.byWidgetPredicate(
(widget) => widget is Text && widget.data?.replaceAll('\u200B', '') == label,
);
void main() {
testWidgets('selection callback carries the exact definition key', (
tester,
) async {
final picked = <String>[];
await tester.pumpWidget(
_material(GraphStageNode(node: _success, onSelected: picked.add)),
);
await tester.tap(find.byType(GraphStageNode));
await tester.pump();
expect(picked, ['#success']);
_expectSelectable(tester, selected: false);
expect(_semantics(tester).label, 'Success');
});
testWidgets('selected node is announced selected in both native hosts', (
tester,
) async {
await tester.pumpWidget(
_material(
GraphStageNode(node: _stage, selected: true, onSelected: (_) {}),
),
);
expect(find.byType(Card), findsOneWidget);
expect(find.byType(InkWell), findsOneWidget);
_expectSelectable(tester, selected: true);
await tester.pumpWidget(
_cupertino(
GraphStageNode(node: _stage, selected: true, onSelected: (_) {}),
),
);
expect(find.byType(CupertinoButton), findsOneWidget);
expect(find.byType(Card), findsNothing);
_expectSelectable(tester, selected: true);
});
testWidgets('unselected node is not announced selected', (tester) async {
await tester.pumpWidget(
_material(GraphStageNode(node: _stage, onSelected: (_) {})),
);
expect(find.byType(Card), findsOneWidget);
_expectSelectable(tester, selected: false);
});
testWidgets('keyboard activation selects the node', (tester) async {
for (final wrap in [_material, _cupertino]) {
final picked = <String>[];
await tester.pumpWidget(
wrap(GraphStageNode(node: _stage, onSelected: picked.add)),
);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(picked, ['build']);
}
});
testWidgets('keyboard selection keeps focus inside the material node', (
tester,
) async {
var selected = false;
await tester.pumpWidget(
_material(
StatefulBuilder(
builder: (context, setState) => GraphStageNode(
node: _stage,
selected: selected,
onSelected: (_) => setState(() => selected = true),
),
),
),
);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(selected, isTrue);
final focused = FocusManager.instance.primaryFocus;
expect(focused?.context, isNotNull);
expect(
focused?.context?.findAncestorWidgetOfExactType<Card>(),
isNotNull,
reason: 'switching card emphasis must not drop keyboard focus',
);
});
testWidgets('long label wraps unshortened in a narrow 2x layout', (
tester,
) async {
const label = 'implementer-with-an-unshortened-stage-label';
const node = GraphNode(key: label, terminal: false, stageIndex: 0);
for (final wrap in [_material, _cupertino]) {
await tester.pumpWidget(
wrap(
_scaled(
SizedBox(
width: 150,
child: GraphStageNode(node: node, onSelected: (_) {}),
),
),
),
);
expect(tester.takeException(), isNull);
final text = tester.widget<Text>(_visual(label));
expect(text.data!.replaceAll('\u200B', ''), label);
expect(text.maxLines, isNull);
expect(text.overflow, isNull);
final paragraph = tester.renderObject<RenderParagraph>(_visual(label));
expect(paragraph.size.width, lessThanOrEqualTo(150));
expect(
paragraph.size.height,
greaterThan(50),
reason: 'the 2x label must occupy more than one 2x text line',
);
// No glyph may paint outside the paragraph: every laid-out line,
// including a hyphen-broken segment, fits the width the control gave it.
final painter = TextPainter(
text: paragraph.text,
textDirection: paragraph.textDirection,
textScaler: paragraph.textScaler,
textAlign: paragraph.textAlign,
)..layout(maxWidth: paragraph.size.width);
expect(
painter.computeLineMetrics().every(
(line) => line.width <= paragraph.size.width + 0.5,
),
isTrue,
reason: 'an unshortened label must wrap, not paint over the control',
);
}
});
testWidgets('terminal shows its definition label and no invented status', (
tester,
) async {
for (final node in [_success, _failure]) {
await tester.pumpWidget(
_material(GraphStageNode(node: node, onSelected: (_) {})),
);
final texts = tester
.widgetList<Text>(find.byType(Text))
.map((text) => text.data?.replaceAll('\u200B', ''))
.toList();
expect(texts, [node.label]);
expect(texts.join(' ').toLowerCase(), isNot(contains('executed')));
expect(texts.join(' ').toLowerCase(), isNot(contains('visited')));
expect(_semantics(tester).label, node.label);
expect(_semantics(tester).label, isNot(contains('\u200B')));
}
});
testWidgets('a recorded status is shown verbatim', (tester) async {
await tester.pumpWidget(
_cupertino(
GraphStageNode(
node: _stage,
recordedStatus: 'failed',
onSelected: (_) {},
),
),
);
expect(_visual('build'), findsOneWidget);
expect(_visual('failed'), findsOneWidget);
final label = _semantics(tester).label;
expect(label, contains('build'));
expect(label, contains('failed'));
expect(label, isNot(contains('\u200B')));
});
testWidgets('a blank recorded status adds no line', (tester) async {
await tester.pumpWidget(
_material(
GraphStageNode(node: _stage, recordedStatus: ' ', onSelected: (_) {}),
),
);
expect(find.byType(Text), findsOneWidget);
expect(_semantics(tester).label, 'build');
});
}
@@ -0,0 +1,192 @@
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/cancel_eligibility.dart';
import 'package:pipelines_app/features/runs/actions/cancel_wording.dart';
import 'cancel_test_support.dart';
void main() {
test('cancel eligibility matches the web canCancel exactly', () {
final cases = <(String, JsonMap, bool)>[
('executing run', executingRun(), true),
(
'waiting while a session export is pending',
executingRun(executing: false, status: 'waiting', exportPending: 2),
true,
),
(
'waiting with no pending export',
executingRun(executing: false, status: 'waiting'),
false,
),
(
'status says running but the run is not executing',
executingRun(executing: false),
false,
),
(
'cancellation already requested',
executingRun(cancelRequested: true),
false,
),
('cleanup unconfirmed', executingRun(cleanupUnconfirmed: true), false),
(
'completed run',
executingRun(executing: false, status: 'succeeded'),
false,
),
('failed run', executingRun(executing: false, status: 'failed'), false),
];
for (final (label, run, expected) in cases) {
expect(canCancelRun(run), expected, reason: label);
}
expect(canCancelRun(null), isFalse);
});
testWidgets(
'material cancel asks first, Keep sends nothing, then sends the envelope',
(tester) async {
final accepted = acceptedCancelRun();
final gateway = FakeCancelGateway(
(type, fields) async => {'run_detail': accepted},
);
final changed = <JsonMap>[];
await tester.pumpWidget(
cancelApp(
CancelHost(
gateway: gateway,
initial: executingRun(),
changed: changed,
),
cupertino: false,
),
);
expect(find.byKey(cancelActionKey), findsOneWidget);
expect(find.byType(FilledButton), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text(cancelDialogTitle(7)), findsOneWidget);
expect(find.text(cancelDialogMessage), findsOneWidget);
expect(find.text(cancelKeepLabel), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(cancelKeepKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(find.byKey(cancelActionKey), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(cancelConfirmKey));
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['cancel_run']);
expect(gateway.calls.single.fields, {'run_id': 7});
expect(changed.single, equals(accepted));
expect(find.byType(AlertDialog), findsNothing);
expect(find.byKey(cancelActionKey), findsNothing);
},
);
testWidgets(
'cupertino cancel uses a native prompt and sends only on confirm',
(tester) async {
final accepted = acceptedCancelRun();
final gateway = FakeCancelGateway(
(type, fields) async => {'run_detail': accepted},
);
final changed = <JsonMap>[];
await tester.pumpWidget(
cancelApp(
CancelHost(
gateway: gateway,
initial: executingRun(),
changed: changed,
),
cupertino: true,
),
);
expect(find.byKey(cancelActionKey), findsOneWidget);
expect(find.byType(CupertinoButton), findsOneWidget);
expect(find.byType(FilledButton), findsNothing);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
expect(find.text(cancelDialogTitle(7)), findsOneWidget);
expect(find.text(cancelDialogMessage), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(cancelKeepKey));
await tester.pumpAndSettle();
expect(gateway.calls, isEmpty);
expect(find.byType(CupertinoAlertDialog), findsNothing);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(cancelConfirmKey));
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['cancel_run']);
expect(gateway.calls.single.fields, {'run_id': 7});
expect(changed.single, equals(accepted));
expect(find.byType(CupertinoAlertDialog), findsNothing);
expect(find.byKey(cancelActionKey), findsNothing);
},
);
testWidgets('the action is absent for runs the web does not cancel', (
tester,
) async {
final gateway = FakeCancelGateway(
(type, fields) async => {'run_detail': executingRun()},
);
final changed = <JsonMap>[];
final cases = <(String, JsonMap, bool)>[
('executing', executingRun(), true),
(
'export wait',
executingRun(executing: false, status: 'waiting', exportPending: 1),
true,
),
(
'no export wait',
executingRun(executing: false, status: 'waiting'),
false,
),
('stale running status', executingRun(executing: false), false),
('already stopping', executingRun(cancelRequested: true), false),
('cleanup unconfirmed', executingRun(cleanupUnconfirmed: true), false),
('finished', executingRun(executing: false, status: 'succeeded'), false),
];
for (final (label, run, visible) in cases) {
await tester.pumpWidget(
cancelApp(
CancelHost(
key: ValueKey(label),
gateway: gateway,
initial: run,
changed: changed,
),
cupertino: false,
),
);
expect(
find.byKey(cancelActionKey),
visible ? findsOneWidget : findsNothing,
reason: label,
);
}
expect(gateway.calls, isEmpty);
expect(changed, isEmpty);
});
}
@@ -0,0 +1,271 @@
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/core/transport/connection_state.dart';
import 'package:pipelines_app/features/runs/actions/cancel_wording.dart';
import 'cancel_test_support.dart';
Future<void> _pump(
WidgetTester tester,
FakeCancelGateway gateway,
List<JsonMap> changed, {
bool cupertino = false,
double textScale = 1,
JsonMap? run,
}) async {
await tester.pumpWidget(
cancelApp(
CancelHost(
gateway: gateway,
initial: run ?? executingRun(),
changed: changed,
),
cupertino: cupertino,
textScale: textScale,
),
);
}
Future<void> _openAndConfirm(WidgetTester tester) async {
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(cancelConfirmKey));
}
void main() {
testWidgets('a refusal stays visible and delivers the resynced run', (
tester,
) async {
const refusal = 'run 7 already completed; nothing to cancel';
final refreshed = executingRun(executing: false, status: 'succeeded');
final gateway = FakeCancelGateway((type, fields) async {
if (type == 'cancel_run') throw const ProtocolError(refusal);
expect(type, 'get_run');
return {'run_detail': refreshed};
});
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _openAndConfirm(tester);
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']);
expect(gateway.calls.first.fields, {'run_id': 7});
expect(gateway.calls.last.fields, {'run_id': 7});
expect(find.text(refusal), findsOneWidget);
expect(find.byKey(cancelErrorKey), findsOneWidget);
expect(find.byType(AlertDialog), findsOneWidget);
expect(changed.single, equals(refreshed));
expect(find.byKey(cancelActionKey), findsNothing);
});
testWidgets('a failed resync never hides the refusal or invents a run', (
tester,
) async {
const refusal = 'server refused to stop the run';
final gateway = FakeCancelGateway((type, fields) async {
if (type == 'cancel_run') throw const ProtocolError(refusal);
throw const NotConnectedError();
});
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _openAndConfirm(tester);
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']);
expect(find.text(refusal), findsOneWidget);
expect(find.byType(AlertDialog), findsOneWidget);
expect(changed, isEmpty);
expect(find.byKey(cancelActionKey), findsOneWidget);
});
testWidgets('a refusal and Keep do not wait for the resync', (tester) async {
const refusal = 'run 7 is already stopping';
final resync = Completer<JsonMap>();
final gateway = FakeCancelGateway((type, fields) {
if (type == 'cancel_run') throw const ProtocolError(refusal);
return resync.future;
});
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _openAndConfirm(tester);
await tester.pump();
expect(find.text(refusal), findsOneWidget);
expect(
tester.widget<TextButton>(find.byKey(cancelKeepKey)).onPressed,
isNotNull,
);
expect(
tester.widget<FilledButton>(find.byKey(cancelConfirmKey)).onPressed,
isNull,
);
expect(changed, isEmpty);
await tester.tap(find.byKey(cancelKeepKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
resync.complete({
'run_detail': executingRun(executing: false, status: 'succeeded'),
});
await tester.pump();
expect(tester.takeException(), isNull);
expect(changed.single['status'], 'succeeded');
});
testWidgets('a late resync after disposal is ignored safely', (tester) async {
final resync = Completer<JsonMap>();
final gateway = FakeCancelGateway((type, fields) {
if (type == 'cancel_run') throw const ProtocolError('already stopped');
return resync.future;
});
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _openAndConfirm(tester);
await tester.pump();
expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']);
await tester.pumpWidget(const SizedBox());
resync.complete({'run_detail': acceptedCancelRun()});
await tester.pump();
expect(tester.takeException(), isNull);
expect(changed, isEmpty);
});
testWidgets('an ineligible resync disables confirm but keeps the refusal', (
tester,
) async {
const refusal = 'run 7 already completed; nothing to cancel';
final finished = executingRun(executing: false, status: 'succeeded');
final gateway = FakeCancelGateway((type, fields) async {
if (type == 'cancel_run') throw const ProtocolError(refusal);
return {'run_detail': finished};
});
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _openAndConfirm(tester);
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']);
expect(find.text(refusal), findsOneWidget);
expect(
tester.widget<FilledButton>(find.byKey(cancelConfirmKey)).onPressed,
isNull,
);
expect(
tester.widget<TextButton>(find.byKey(cancelKeepKey)).onPressed,
isNotNull,
);
await tester.tap(find.byKey(cancelConfirmKey));
await tester.pump();
expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']);
await tester.tap(find.byKey(cancelKeepKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(find.byKey(cancelActionKey), findsNothing);
expect(changed.single, equals(finished));
});
testWidgets(
'confirm cannot submit twice while the cancellation is in flight',
(tester) async {
final reply = Completer<JsonMap>();
final gateway = FakeCancelGateway((type, fields) => reply.future);
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
final confirm = find.byKey(cancelConfirmKey);
await tester.tap(confirm);
await tester.tap(confirm);
await tester.pump();
expect(
gateway.calls.where((call) => call.type == 'cancel_run'),
hasLength(1),
);
expect(
tester.widget<FilledButton>(find.byKey(cancelConfirmKey)).onPressed,
isNull,
);
expect(
tester.widget<TextButton>(find.byKey(cancelKeepKey)).onPressed,
isNull,
);
expect(find.byType(AlertDialog), findsOneWidget);
reply.complete({'run_detail': acceptedCancelRun()});
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(changed, hasLength(1));
},
);
testWidgets('a late reply after disposal is ignored safely', (tester) async {
final reply = Completer<JsonMap>();
final gateway = FakeCancelGateway((type, fields) => reply.future);
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _openAndConfirm(tester);
await tester.pump();
expect(gateway.calls, hasLength(1));
await tester.pumpWidget(const SizedBox());
reply.complete({'run_detail': acceptedCancelRun()});
await tester.pump();
expect(tester.takeException(), isNull);
expect(changed, isEmpty);
});
testWidgets('both prompts fit 2x text at a narrow width', (tester) async {
tester.view.physicalSize = const Size(320, 480);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
for (final cupertino in [false, true]) {
final gateway = FakeCancelGateway(
(type, fields) async => {'run_detail': acceptedCancelRun()},
);
await _pump(
tester,
gateway,
<JsonMap>[],
cupertino: cupertino,
textScale: 2,
);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino');
expect(find.text(cancelDialogTitle(7)), findsOneWidget);
expect(find.text(cancelDialogMessage), findsOneWidget);
expect(
cupertino
? find.byType(CupertinoAlertDialog)
: find.byType(AlertDialog),
findsOneWidget,
);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(cancelKeepKey));
await tester.pumpAndSettle();
}
});
}
@@ -0,0 +1,101 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/actions/cancel_run_action.dart';
typedef CancelHandler = Future<JsonMap> Function(String type, JsonMap fields);
/// A fake gateway that records every request and never owns a socket.
class FakeCancelGateway implements ApiGateway {
FakeCancelGateway(this.handler);
final CancelHandler handler;
final List<({String type, JsonMap fields})> calls = [];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
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();
}
JsonMap executingRun({
num id = 7,
bool executing = true,
String status = 'running',
int exportPending = 0,
bool cancelRequested = false,
bool cleanupUnconfirmed = false,
}) => {
'id': id,
'title': 'Nightly build',
'status': status,
'executing': executing,
'export_pending_sequence': exportPending,
'cancel_requested': cancelRequested,
'cleanup_unconfirmed': cleanupUnconfirmed,
};
JsonMap acceptedCancelRun() =>
executingRun(executing: false, status: 'canceled', cancelRequested: true);
/// Owns the run like a run-detail screen would, so the callback's returned
/// server detail is what the action renders next.
class CancelHost extends StatefulWidget {
const CancelHost({
super.key,
required this.gateway,
required this.initial,
required this.changed,
});
final FakeCancelGateway gateway;
final JsonMap initial;
final List<JsonMap> changed;
@override
State<CancelHost> createState() => _CancelHostState();
}
class _CancelHostState extends State<CancelHost> {
late JsonMap _run = widget.initial;
@override
Widget build(BuildContext context) {
return CancelRunAction(
run: _run,
gateway: widget.gateway,
onRunChanged: (run) {
widget.changed.add(run);
setState(() => _run = run);
},
);
}
}
Widget cancelApp(
Widget child, {
required bool cupertino,
double textScale = 1,
}) {
Widget media(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: app!,
);
if (cupertino) {
return CupertinoApp(
builder: media,
home: CupertinoPageScaffold(child: Center(child: child)),
);
}
return MaterialApp(
builder: media,
home: Scaffold(body: Center(child: child)),
);
}
@@ -0,0 +1,265 @@
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/decision_action.dart';
import 'package:pipelines_app/features/runs/actions/decision_wording.dart';
typedef _Handler = Future<JsonMap> Function(String type, JsonMap fields);
class _FakeGateway implements ApiGateway {
_FakeGateway(this.handler);
final _Handler handler;
final List<({String type, JsonMap fields})> calls = [];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
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();
}
JsonMap _waitingRun({
String status = 'waiting',
int exportPending = 0,
String type = 'human',
List<String> options = const ['go', 'skip'],
}) => {
'id': 7,
'title': 'Report',
'name': 'Build',
'status': status,
'current_stage': 'human',
'export_pending_sequence': exportPending,
'graph': {
'stages': [
{
'key': 'human',
'type': type,
'prompt': 'Graph prompt',
'edges': {'go': '#', 'skip': 'finish'},
},
],
},
'steps': [
{
'sequence': 1,
'status': 'waiting',
'stage': 'human',
'output': {'prompt': 'Ship it?', 'options': options},
},
],
};
JsonMap _decided() => {
..._waitingRun(),
'status': 'succeeded',
'steps': const <JsonMap>[],
};
Widget _app(Widget child, {required bool cupertino, double textScale = 1}) {
if (cupertino) {
return CupertinoApp(
builder: (context, app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: app!,
),
home: CupertinoPageScaffold(child: Center(child: child)),
);
}
return MaterialApp(
builder: (context, app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: app!,
),
home: Scaffold(body: Center(child: child)),
);
}
Future<void> _pump(
WidgetTester tester,
_FakeGateway gateway,
JsonMap run, {
required bool cupertino,
required List<JsonMap> changed,
double textScale = 1,
}) async {
await tester.pumpWidget(
_app(
HumanDecisionAction(
run: run,
gateway: gateway,
onRunChanged: changed.add,
),
cupertino: cupertino,
textScale: textScale,
),
);
}
Future<void> _open(WidgetTester tester) async {
await tester.tap(find.byKey(decisionActionKey));
await tester.pumpAndSettle();
}
void main() {
testWidgets(
'material decision waits for option and confirm, then sends exact fields',
(tester) async {
final gateway = _FakeGateway(
(type, fields) async => {
'run_detail': type == 'decide_run' ? _decided() : _waitingRun(),
},
);
final changed = <JsonMap>[];
await _pump(
tester,
gateway,
_waitingRun(),
cupertino: false,
changed: changed,
);
expect(find.byKey(decisionActionKey), findsOneWidget);
expect(find.byType(FilledButton), findsOneWidget);
expect(gateway.calls, isEmpty);
await _open(tester);
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text(decisionWaitingTitle), findsOneWidget);
expect(find.text('Ship it?'), findsOneWidget);
expect(find.text('→ SUCCESS'), findsOneWidget);
expect(gateway.calls, isEmpty);
final confirm = find.widgetWithText(FilledButton, decisionConfirmLabel);
expect(tester.widget<FilledButton>(confirm).onPressed, isNull);
await tester.tap(find.text('go'));
await tester.pump();
expect(gateway.calls, isEmpty);
expect(tester.widget<FilledButton>(confirm).onPressed, isNotNull);
await tester.enterText(find.byKey(decisionFeedbackKey), ' looks good ');
await tester.tap(find.text(decisionConfirmLabel));
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['decide_run']);
expect(gateway.calls.single.fields, {
'run_id': 7,
'stage': 'human',
'option': 'go',
'feedback': 'looks good',
});
expect(changed.single['status'], 'succeeded');
expect(find.byType(AlertDialog), findsNothing);
expect(find.byKey(decisionActionKey), findsNothing);
},
);
testWidgets(
'cupertino decision uses a native dialog and omits empty feedback',
(tester) async {
final gateway = _FakeGateway(
(type, fields) async => {
'run_detail': type == 'decide_run' ? _decided() : _waitingRun(),
},
);
final changed = <JsonMap>[];
await _pump(
tester,
gateway,
_waitingRun(),
cupertino: true,
changed: changed,
);
expect(find.byKey(decisionActionKey), findsOneWidget);
expect(find.byType(FilledButton), findsNothing);
await _open(tester);
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.text(decisionWaitingTitle), findsOneWidget);
expect(gateway.calls, isEmpty);
final confirm = find.widgetWithText(
CupertinoDialogAction,
decisionConfirmLabel,
);
expect(tester.widget<CupertinoDialogAction>(confirm).onPressed, isNull);
await tester.tap(find.text('skip'));
await tester.pump();
expect(gateway.calls, isEmpty);
await tester.tap(find.text(decisionConfirmLabel));
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['decide_run']);
expect(gateway.calls.single.fields, {
'run_id': 7,
'stage': 'human',
'option': 'skip',
});
expect(changed.single['status'], 'succeeded');
expect(find.byType(CupertinoAlertDialog), findsNothing);
},
);
testWidgets('Cancel dismisses the draft without sending anything', (
tester,
) async {
final gateway = _FakeGateway(
(type, fields) async => {'run_detail': _decided()},
);
final changed = <JsonMap>[];
await _pump(
tester,
gateway,
_waitingRun(),
cupertino: false,
changed: changed,
);
await _open(tester);
await tester.tap(find.text('go'));
await tester.pump();
await tester.enterText(find.byKey(decisionFeedbackKey), 'not sent');
await tester.tap(find.widgetWithText(TextButton, decisionCancelLabel));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(gateway.calls, isEmpty);
expect(changed, isEmpty);
expect(find.byKey(decisionActionKey), findsOneWidget);
});
testWidgets('the action is absent unless a run is genuinely waiting', (
tester,
) async {
final gateway = _FakeGateway(
(type, fields) async => {'run_detail': _waitingRun()},
);
final changed = <JsonMap>[];
for (final (label, run) in [
('not waiting', _waitingRun(status: 'running')),
('export pending', _waitingRun(exportPending: 2)),
('model stage', _waitingRun(type: 'model')),
]) {
await _pump(tester, gateway, run, cupertino: false, changed: changed);
expect(
find.byKey(decisionActionKey),
findsNothing,
reason: '$label must not offer a decision',
);
}
expect(gateway.calls, isEmpty);
expect(changed, isEmpty);
});
}
@@ -0,0 +1,351 @@
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/core/transport/connection_state.dart';
import 'package:pipelines_app/features/runs/actions/decision_action.dart';
import 'package:pipelines_app/features/runs/actions/decision_wording.dart';
typedef _Handler = Future<JsonMap> Function(String type, JsonMap fields);
class _FakeGateway implements ApiGateway {
_FakeGateway(this.handler);
final _Handler handler;
final List<({String type, JsonMap fields})> calls = [];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
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();
}
JsonMap _waitingRun() => {
'id': 7,
'title': 'Report',
'status': 'waiting',
'current_stage': 'human',
'graph': {
'stages': [
{
'key': 'human',
'type': 'human',
'prompt': 'Graph prompt',
'edges': {'go': '#', 'skip': 'finish'},
},
],
},
'steps': [
{
'sequence': 1,
'status': 'waiting',
'stage': 'human',
'output': {
'prompt': 'Ship it?',
'options': ['go', 'skip'],
},
},
],
};
JsonMap _decided() => {
..._waitingRun(),
'status': 'succeeded',
'steps': const <JsonMap>[],
};
Widget _app(Widget child, {required bool cupertino, double textScale = 1}) {
Widget media(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: app!,
);
if (cupertino) {
return CupertinoApp(
builder: media,
home: CupertinoPageScaffold(child: Center(child: child)),
);
}
return MaterialApp(
builder: media,
home: Scaffold(body: Center(child: child)),
);
}
Future<void> _pump(
WidgetTester tester,
_FakeGateway gateway,
List<JsonMap> changed, {
bool cupertino = false,
double textScale = 1,
}) async {
await tester.pumpWidget(
_app(
HumanDecisionAction(
run: _waitingRun(),
gateway: gateway,
onRunChanged: changed.add,
),
cupertino: cupertino,
textScale: textScale,
),
);
}
Future<void> _chooseGo(WidgetTester tester, {String feedback = ''}) async {
await tester.tap(find.byKey(decisionActionKey));
await tester.pumpAndSettle();
await tester.tap(find.text('go'));
await tester.pump();
if (feedback.isNotEmpty) {
await tester.enterText(find.byKey(decisionFeedbackKey), feedback);
}
}
void main() {
testWidgets('a refusal stays visible and keeps the selected draft', (
tester,
) async {
const refusal = 'option "go" is not a valid outcome; choose one of: skip';
final gateway = _FakeGateway((type, fields) async {
if (type == 'decide_run') throw const ProtocolError(refusal);
expect(type, 'get_run');
return {
'run_detail': {
..._waitingRun(),
'status': 'failed',
'steps': const <JsonMap>[],
},
};
});
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _chooseGo(tester, feedback: ' keep me ');
await tester.tap(find.text(decisionConfirmLabel));
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']);
expect(gateway.calls.last.fields, {'run_id': 7});
expect(find.text(refusal), findsOneWidget);
expect(find.byType(AlertDialog), findsOneWidget);
expect(
tester
.widget<RadioGroup<String>>(find.byType(RadioGroup<String>))
.groupValue,
'go',
);
expect(
tester
.widget<TextField>(find.byKey(decisionFeedbackKey))
.controller
?.text,
' keep me ',
);
expect(changed.single['status'], 'failed');
expect(find.byKey(decisionActionKey), findsNothing);
});
testWidgets('a refusal is shown before the resync keeps the draft', (
tester,
) async {
const refusal = 'option "go" is no longer valid';
final resync = Completer<JsonMap>();
final gateway = _FakeGateway((type, fields) {
if (type == 'decide_run') throw const ProtocolError(refusal);
return resync.future;
});
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _chooseGo(tester, feedback: ' keep me ');
await tester.tap(find.text(decisionConfirmLabel));
await tester.pump();
expect(find.text(refusal), findsOneWidget);
expect(find.byType(AlertDialog), findsOneWidget);
expect(
tester
.widget<RadioGroup<String>>(find.byType(RadioGroup<String>))
.groupValue,
'go',
);
expect(
tester
.widget<TextField>(find.byKey(decisionFeedbackKey))
.controller
?.text,
' keep me ',
);
expect(
tester
.widget<TextButton>(
find.widgetWithText(TextButton, decisionCancelLabel),
)
.onPressed,
isNotNull,
);
expect(changed, isEmpty);
resync.complete({'run_detail': _decided()});
await tester.pumpAndSettle();
expect(find.text(refusal), findsOneWidget);
expect(
tester
.widget<FilledButton>(
find.widgetWithText(FilledButton, decisionConfirmLabel),
)
.onPressed,
isNull,
);
expect(changed.single['status'], 'succeeded');
});
testWidgets('a failed resync keeps the draft and allows a retry', (
tester,
) async {
const refusal = 'server refused the decision';
final gateway = _FakeGateway((type, fields) async {
if (type == 'decide_run') throw const ProtocolError(refusal);
throw const NotConnectedError();
});
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _chooseGo(tester, feedback: ' keep me ');
await tester.tap(find.text(decisionConfirmLabel));
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']);
expect(find.text(refusal), findsOneWidget);
expect(
tester
.widget<RadioGroup<String>>(find.byType(RadioGroup<String>))
.groupValue,
'go',
);
expect(
tester
.widget<FilledButton>(
find.widgetWithText(FilledButton, decisionConfirmLabel),
)
.onPressed,
isNotNull,
);
expect(changed, isEmpty);
});
testWidgets('a late resync after disposal is ignored safely', (tester) async {
final resync = Completer<JsonMap>();
final gateway = _FakeGateway((type, fields) {
if (type == 'decide_run') throw const ProtocolError('no longer waiting');
return resync.future;
});
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _chooseGo(tester);
await tester.tap(find.text(decisionConfirmLabel));
await tester.pump();
expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']);
await tester.pumpWidget(const SizedBox());
resync.complete({'run_detail': _decided()});
await tester.pump();
expect(tester.takeException(), isNull);
expect(changed, isEmpty);
});
testWidgets('confirm cannot submit twice while the decision is in flight', (
tester,
) async {
final reply = Completer<JsonMap>();
final gateway = _FakeGateway((type, fields) => reply.future);
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _chooseGo(tester);
final confirm = find.text(decisionConfirmLabel);
await tester.tap(confirm);
await tester.tap(confirm);
await tester.pump();
expect(
gateway.calls.where((call) => call.type == 'decide_run'),
hasLength(1),
);
expect(find.text(decisionSendingLabel), findsOneWidget);
expect(
tester
.widget<TextButton>(
find.widgetWithText(TextButton, decisionCancelLabel),
)
.onPressed,
isNull,
);
reply.complete({'run_detail': _decided()});
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(changed, hasLength(1));
});
testWidgets('a late reply after disposal is ignored safely', (tester) async {
final reply = Completer<JsonMap>();
final gateway = _FakeGateway((type, fields) => reply.future);
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _chooseGo(tester);
await tester.tap(find.text(decisionConfirmLabel));
await tester.pump();
expect(gateway.calls, hasLength(1));
await tester.pumpWidget(const SizedBox());
reply.complete({'run_detail': _decided()});
await tester.pump();
expect(tester.takeException(), isNull);
expect(changed, isEmpty);
});
testWidgets('both prompts fit 2x text at a narrow width', (tester) async {
tester.view.physicalSize = const Size(320, 480);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
for (final cupertino in [false, true]) {
final gateway = _FakeGateway(
(type, fields) async => {'run_detail': _decided()},
);
await _pump(
tester,
gateway,
<JsonMap>[],
cupertino: cupertino,
textScale: 2,
);
await tester.tap(find.byKey(decisionActionKey));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino');
expect(find.text(decisionWaitingTitle), findsOneWidget);
expect(find.text('Ship it?'), findsOneWidget);
expect(
cupertino
? find.byType(CupertinoAlertDialog)
: find.byType(AlertDialog),
findsOneWidget,
);
}
});
}
@@ -0,0 +1,245 @@
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_eligibility.dart';
import 'package:pipelines_app/features/runs/actions/retry_intent.dart';
import 'package:pipelines_app/features/runs/actions/retry_wording.dart';
import 'retry_test_support.dart';
void main() {
test('retry eligibility matches the web canRetry exactly', () {
final cases = <(String, JsonMap, bool)>[
('failed and stopped', failedRun(), true),
('failed but still executing', failedRun(executing: true), false),
('running', failedRun(status: 'running'), false),
('waiting', failedRun(status: 'waiting'), false),
('succeeded', failedRun(status: 'succeeded'), false),
('canceled', failedRun(status: 'canceled'), false),
];
for (final (label, run, expected) in cases) {
expect(canRetryRun(run), expected, reason: label);
}
expect(canRetryRun(null), isFalse);
expect(retryRunId(failedRun()), 7);
expect(retryRunId({'id': '7'}), isNull);
});
test('a generated retry key is bounded, run-scoped and fresh', () {
final first = newRetryRequestKey(7);
final second = newRetryRequestKey(7);
expect(first, startsWith('app-retry-7-'));
expect(first.length, lessThanOrEqualTo(128));
expect(second.length, lessThanOrEqualTo(128));
expect(first, isNot(second));
expect(
newRetryRequestKey(7, now: DateTime.utc(2026, 1, 1), random: 36),
'app-retry-7-${DateTime.utc(2026, 1, 1).microsecondsSinceEpoch}-10',
);
});
testWidgets(
'material retry asks first, Keep sends nothing, then omits retry_mode',
(tester) async {
final accepted = retriedRun();
final gateway = FakeRetryGateway(
(type, fields) async => {'run_detail': accepted},
);
final changed = <JsonMap>[];
await pumpRetry(tester, gateway: gateway, changed: changed);
expect(find.byKey(retryActionKey), findsOneWidget);
expect(find.byType(FilledButton), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text(retryDialogTitle(7)), findsOneWidget);
expect(find.text(retryDialogMessage), findsOneWidget);
expect(
find.descendant(
of: find.byType(AlertDialog),
matching: find.text(retryConfirmLabel),
),
findsOneWidget,
);
expect(find.text(restartConfirmLabel), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(retryKeepKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(find.byKey(retryActionKey), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryConfirmKey));
await tester.pumpAndSettle();
expect(gateway.retries, hasLength(1));
final fields = gateway.retries.single.fields;
expect(fields.keys, containsAll(<String>['run_id', 'request_key']));
expect(fields.containsKey('retry_mode'), isFalse);
expect(fields['run_id'], 7);
expect(fields['request_key'], startsWith('app-retry-7-'));
expect(fields['request_key'].length, lessThanOrEqualTo(128));
expect(changed.single, equals(accepted));
expect(find.byType(AlertDialog), findsNothing);
expect(find.byKey(retryActionKey), findsNothing);
},
);
testWidgets(
'material restart has its own confirmation and sends retry_mode',
(tester) async {
final accepted = retriedRun();
final gateway = FakeRetryGateway(
(type, fields) async => {'run_detail': accepted},
);
final changed = <JsonMap>[];
await pumpRetry(tester, gateway: gateway, changed: changed);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryRestartKey));
await tester.pumpAndSettle();
expect(find.text(restartDialogTitle(7)), findsOneWidget);
expect(find.text(restartDialogMessage), findsOneWidget);
expect(find.text(retryDialogTitle(7)), findsNothing);
expect(find.text(retryDialogMessage), findsNothing);
expect(find.text(restartConfirmLabel), findsOneWidget);
expect(find.byKey(retryRestartKey), findsNothing);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(retryConfirmKey));
await tester.pumpAndSettle();
expect(gateway.retries, hasLength(1));
final fields = gateway.retries.single.fields;
expect(fields['run_id'], 7);
expect(fields['retry_mode'], 'restart');
expect(fields['request_key'], startsWith('app-retry-7-'));
expect(changed.single, equals(accepted));
expect(find.byType(AlertDialog), findsNothing);
},
);
testWidgets(
'cupertino retry uses a native prompt and sends only on confirm',
(tester) async {
final accepted = retriedRun();
final gateway = FakeRetryGateway(
(type, fields) async => {'run_detail': accepted},
);
final changed = <JsonMap>[];
await pumpRetry(
tester,
gateway: gateway,
changed: changed,
cupertino: true,
);
expect(find.byKey(retryActionKey), findsOneWidget);
expect(find.byType(CupertinoButton), findsOneWidget);
expect(find.byType(FilledButton), findsNothing);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
expect(find.text(retryDialogTitle(7)), findsOneWidget);
expect(find.text(retryDialogMessage), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(retryKeepKey));
await tester.pumpAndSettle();
expect(gateway.calls, isEmpty);
expect(find.byType(CupertinoAlertDialog), findsNothing);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryConfirmKey));
await tester.pumpAndSettle();
expect(gateway.retries, hasLength(1));
final fields = gateway.retries.single.fields;
expect(fields['run_id'], 7);
expect(fields.containsKey('retry_mode'), isFalse);
expect(fields['request_key'], startsWith('app-retry-7-'));
expect(changed.single, equals(accepted));
expect(find.byType(CupertinoAlertDialog), findsNothing);
},
);
testWidgets('cupertino restart switches to the restart confirmation', (
tester,
) async {
final gateway = FakeRetryGateway(
(type, fields) async => {'run_detail': retriedRun()},
);
await pumpRetry(
tester,
gateway: gateway,
changed: <JsonMap>[],
cupertino: true,
);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryRestartKey));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.text(restartDialogTitle(7)), findsOneWidget);
expect(find.text(restartDialogMessage), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(retryConfirmKey));
await tester.pumpAndSettle();
expect(gateway.retries.single.fields['retry_mode'], 'restart');
});
testWidgets('the action is absent for runs the web does not retry', (
tester,
) async {
final gateway = FakeRetryGateway(
(type, fields) async => {'run_detail': retriedRun()},
);
final changed = <JsonMap>[];
final cases = <(String, JsonMap, bool)>[
('failed', failedRun(), true),
('executing', failedRun(executing: true), false),
('running', failedRun(status: 'running'), false),
('waiting', failedRun(status: 'waiting'), false),
('succeeded', failedRun(status: 'succeeded'), false),
('canceled', failedRun(status: 'canceled'), false),
];
for (final cupertino in [false, true]) {
for (final (label, run, visible) in cases) {
await tester.pumpWidget(
retryApp(
RetryHost(
key: ValueKey('$label-$cupertino'),
gateway: gateway,
initial: run,
changed: changed,
),
cupertino: cupertino,
),
);
expect(
find.byKey(retryActionKey),
visible ? findsOneWidget : findsNothing,
reason: '$label cupertino=$cupertino',
);
}
}
expect(gateway.calls, isEmpty);
expect(changed, isEmpty);
});
}
@@ -0,0 +1,223 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'package:pipelines_app/features/runs/actions/retry_eligibility.dart';
import 'package:pipelines_app/features/runs/actions/retry_wording.dart';
import 'retry_test_support.dart';
Future<void> _openAndConfirm(WidgetTester tester) async {
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryConfirmKey));
}
void main() {
testWidgets('a refusal is shown at once and Keep does not wait for resync', (
tester,
) async {
const refusal = 'run 7 is still executing; wait for it to stop completely';
final resync = Completer<JsonMap>();
final gateway = FakeRetryGateway((type, fields) {
if (type == 'retry_run') throw const ProtocolError(refusal);
return resync.future;
});
final changed = <JsonMap>[];
await pumpRetry(tester, gateway: gateway, changed: changed);
await _openAndConfirm(tester);
await tester.pump();
expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']);
expect(find.text(refusal), findsOneWidget);
expect(find.byKey(retryErrorKey), findsOneWidget);
expect(
tester.widget<TextButton>(find.byKey(retryKeepKey)).onPressed,
isNotNull,
);
expect(
tester.widget<FilledButton>(find.byKey(retryConfirmKey)).onPressed,
isNull,
);
expect(changed, isEmpty);
await tester.tap(find.byKey(retryKeepKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
resync.complete({'run_detail': failedRun(status: 'succeeded')});
await tester.pump();
await tester.pump();
expect(tester.takeException(), isNull);
expect(changed.single['status'], 'succeeded');
expect(find.byKey(retryActionKey), findsNothing);
});
testWidgets('server truth that is ineligible blocks a repeat action', (
tester,
) async {
const refusal = 'only failed runs can be retried';
final finished = failedRun(status: 'succeeded');
final gateway = FakeRetryGateway((type, fields) async {
if (type == 'retry_run') throw const ProtocolError(refusal);
return {'run_detail': finished};
});
final changed = <JsonMap>[];
await pumpRetry(tester, gateway: gateway, changed: changed);
await _openAndConfirm(tester);
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']);
expect(find.text(refusal), findsOneWidget);
expect(
tester.widget<FilledButton>(find.byKey(retryConfirmKey)).onPressed,
isNull,
);
expect(
tester.widget<TextButton>(find.byKey(retryKeepKey)).onPressed,
isNotNull,
);
await tester.tap(find.byKey(retryConfirmKey));
await tester.pump();
expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']);
await tester.tap(find.byKey(retryKeepKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(find.byKey(retryActionKey), findsNothing);
expect(changed.single, equals(finished));
expect(canRetryRun(changed.single), isFalse);
});
testWidgets('a failed recheck keeps the same key for the uncertain request', (
tester,
) async {
const refusal = 'connection dropped while retrying';
var attempts = 0;
final gateway = FakeRetryGateway((type, fields) async {
if (type == 'get_run') throw const NotConnectedError();
attempts += 1;
if (attempts == 1) throw const ProtocolError(refusal);
return {'run_detail': retriedRun()};
});
final changed = <JsonMap>[];
await pumpRetry(tester, gateway: gateway, changed: changed);
await _openAndConfirm(tester);
await tester.pumpAndSettle();
expect(find.text(refusal), findsOneWidget);
expect(
tester.widget<FilledButton>(find.byKey(retryConfirmKey)).onPressed,
isNotNull,
);
expect(gateway.retries, hasLength(1));
await tester.tap(find.byKey(retryConfirmKey));
await tester.pumpAndSettle();
expect(gateway.retries, hasLength(2));
expect(
gateway.retries.last.fields['request_key'],
gateway.retries.first.fields['request_key'],
);
expect(
gateway.retries.every((call) => !call.fields.containsKey('retry_mode')),
isTrue,
);
expect(changed.single, equals(retriedRun()));
expect(find.byType(AlertDialog), findsNothing);
});
testWidgets('a restart retry keeps the mode and key across uncertainty', (
tester,
) async {
var attempts = 0;
final gateway = FakeRetryGateway((type, fields) async {
if (type == 'get_run') throw const NotConnectedError();
attempts += 1;
if (attempts == 1) throw const ProtocolError('network lost');
return {'run_detail': retriedRun()};
});
await pumpRetry(tester, gateway: gateway, changed: <JsonMap>[]);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryRestartKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryConfirmKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryConfirmKey));
await tester.pumpAndSettle();
expect(gateway.retries, hasLength(2));
expect(gateway.retries.first.fields['retry_mode'], 'restart');
expect(gateway.retries.last.fields['retry_mode'], 'restart');
expect(
gateway.retries.last.fields['request_key'],
gateway.retries.first.fields['request_key'],
);
});
testWidgets('a deliberate reopen sends a fresh request key', (tester) async {
final gateway = FakeRetryGateway((type, fields) async {
if (type == 'get_run') throw const NotConnectedError();
throw const ProtocolError('server did not answer');
});
await pumpRetry(tester, gateway: gateway, changed: <JsonMap>[]);
await _openAndConfirm(tester);
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryKeepKey));
await tester.pumpAndSettle();
await _openAndConfirm(tester);
await tester.pumpAndSettle();
expect(gateway.retries, hasLength(2));
expect(
gateway.retries.first.fields['request_key'],
isNot(gateway.retries.last.fields['request_key']),
);
});
testWidgets('a restart after a dismissed resume uses a fresh key', (
tester,
) async {
var attempts = 0;
final gateway = FakeRetryGateway((type, fields) async {
if (type == 'get_run') throw const NotConnectedError();
attempts += 1;
if (attempts == 1) throw const ProtocolError('resume refused');
return {'run_detail': retriedRun()};
});
await pumpRetry(tester, gateway: gateway, changed: <JsonMap>[]);
await _openAndConfirm(tester);
await tester.pumpAndSettle();
// A refusal leaves the prompt open; keep the mode frozen and dismiss.
await tester.tap(find.byKey(retryKeepKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryRestartKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryConfirmKey));
await tester.pumpAndSettle();
expect(gateway.retries, hasLength(2));
expect(gateway.retries.first.fields.containsKey('retry_mode'), isFalse);
expect(gateway.retries.last.fields['retry_mode'], 'restart');
expect(
gateway.retries.first.fields['request_key'],
isNot(gateway.retries.last.fields['request_key']),
);
});
}
@@ -0,0 +1,133 @@
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/core/transport/connection_state.dart';
import 'package:pipelines_app/features/runs/actions/retry_wording.dart';
import 'retry_test_support.dart';
void main() {
testWidgets('confirm cannot submit twice while the retry is in flight', (
tester,
) async {
final reply = Completer<JsonMap>();
final gateway = FakeRetryGateway((type, fields) => reply.future);
final changed = <JsonMap>[];
await pumpRetry(tester, gateway: gateway, changed: changed);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
final confirm = find.byKey(retryConfirmKey);
await tester.tap(confirm);
await tester.tap(confirm);
await tester.pump();
expect(gateway.retries, hasLength(1));
expect(
tester.widget<FilledButton>(find.byKey(retryConfirmKey)).onPressed,
isNull,
);
expect(
tester.widget<TextButton>(find.byKey(retryKeepKey)).onPressed,
isNull,
);
expect(find.byType(AlertDialog), findsOneWidget);
reply.complete({'run_detail': retriedRun()});
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(changed, hasLength(1));
});
testWidgets('a late retry reply after disposal is ignored safely', (
tester,
) async {
final reply = Completer<JsonMap>();
final gateway = FakeRetryGateway((type, fields) => reply.future);
final changed = <JsonMap>[];
await pumpRetry(tester, gateway: gateway, changed: changed);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryConfirmKey));
await tester.pump();
expect(gateway.retries, hasLength(1));
await tester.pumpWidget(const SizedBox());
reply.complete({'run_detail': retriedRun()});
await tester.pump();
expect(tester.takeException(), isNull);
expect(changed, isEmpty);
});
testWidgets('a late resync after disposal is ignored safely', (tester) async {
final resync = Completer<JsonMap>();
final gateway = FakeRetryGateway((type, fields) {
if (type == 'retry_run') throw const ProtocolError('refused');
return resync.future;
});
final changed = <JsonMap>[];
await pumpRetry(tester, gateway: gateway, changed: changed);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryConfirmKey));
await tester.pump();
expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']);
await tester.pumpWidget(const SizedBox());
resync.complete({'run_detail': retriedRun()});
await tester.pump();
expect(tester.takeException(), isNull);
expect(changed, isEmpty);
});
testWidgets('both confirmations fit 2x text at a narrow width', (
tester,
) async {
tester.view.physicalSize = const Size(320, 480);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
for (final cupertino in [false, true]) {
final gateway = FakeRetryGateway(
(type, fields) async => {'run_detail': retriedRun()},
);
await pumpRetry(
tester,
gateway: gateway,
changed: <JsonMap>[],
cupertino: cupertino,
textScale: 2,
);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino');
expect(find.text(retryDialogTitle(7)), findsOneWidget);
expect(find.text(retryDialogMessage), findsOneWidget);
expect(
cupertino
? find.byType(CupertinoAlertDialog)
: find.byType(AlertDialog),
findsOneWidget,
);
await tester.tap(find.byKey(retryRestartKey));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull, reason: 'restart=$cupertino');
expect(find.text(restartDialogTitle(7)), findsOneWidget);
expect(find.text(restartDialogMessage), findsOneWidget);
await tester.tap(find.byKey(retryKeepKey));
await tester.pumpAndSettle();
expect(gateway.calls, isEmpty);
}
});
}
@@ -0,0 +1,112 @@
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_action.dart';
typedef RetryHandler = Future<JsonMap> Function(String type, JsonMap fields);
/// A fake gateway that records every request and never owns a socket.
class FakeRetryGateway implements ApiGateway {
FakeRetryGateway(this.handler);
final RetryHandler handler;
final List<({String type, JsonMap fields})> calls = [];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
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();
Iterable<({String type, JsonMap fields})> get retries =>
calls.where((call) => call.type == 'retry_run');
}
JsonMap failedRun({
num id = 7,
bool executing = false,
String status = 'failed',
String title = 'Nightly build',
}) => {'id': id, 'title': title, 'status': status, 'executing': executing};
JsonMap retriedRun({num id = 8}) =>
failedRun(id: id, status: 'running', executing: true, title: 'Retry of 7');
/// Owns the run like a run-detail screen would, so the callback's returned
/// server detail is what the action renders next.
class RetryHost extends StatefulWidget {
const RetryHost({
super.key,
required this.gateway,
required this.initial,
required this.changed,
});
final FakeRetryGateway gateway;
final JsonMap initial;
final List<JsonMap> changed;
@override
State<RetryHost> createState() => _RetryHostState();
}
class _RetryHostState extends State<RetryHost> {
late JsonMap _run = widget.initial;
@override
Widget build(BuildContext context) {
return RetryRunAction(
run: _run,
gateway: widget.gateway,
onRunChanged: (run) {
widget.changed.add(run);
setState(() => _run = run);
},
);
}
}
Widget retryApp(Widget child, {required bool cupertino, double textScale = 1}) {
Widget media(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: app!,
);
if (cupertino) {
return CupertinoApp(
builder: media,
home: CupertinoPageScaffold(child: Center(child: child)),
);
}
return MaterialApp(
builder: media,
home: Scaffold(body: Center(child: child)),
);
}
Future<void> pumpRetry(
WidgetTester tester, {
required FakeRetryGateway gateway,
required List<JsonMap> changed,
bool cupertino = false,
double textScale = 1,
JsonMap? run,
}) async {
await tester.pumpWidget(
retryApp(
RetryHost(
gateway: gateway,
initial: run ?? failedRun(),
changed: changed,
),
cupertino: cupertino,
textScale: textScale,
),
);
}
@@ -0,0 +1,244 @@
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/core/transport/connection_state.dart';
import 'package:pipelines_app/features/runs/actions/title_action.dart';
import 'package:pipelines_app/features/runs/actions/title_wording.dart';
import 'title_test_support.dart';
String _materialFieldText(WidgetTester tester) =>
tester.widget<TextField>(find.byKey(runTitleFieldKey)).controller!.text;
String _cupertinoFieldText(WidgetTester tester) => tester
.widget<CupertinoTextField>(find.byKey(runTitleFieldKey))
.controller!
.text;
void main() {
testWidgets(
'material rename starts from the stored title, typing sends nothing, '
'Cancel sends nothing and Save sends the exact text',
(tester) async {
final accepted = renamedRun(title: 'Release build');
final gateway = FakeTitleGateway(
(type, fields) async => {'run_detail': accepted},
);
final changed = <JsonMap>[];
await tester.pumpWidget(
titleApp(
TitleHost(gateway: gateway, initial: titledRun(), changed: changed),
cupertino: false,
),
);
expect(find.byKey(runTitleActionKey), findsOneWidget);
expect(find.byType(OutlinedButton), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(runTitleActionKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text(runTitleDialogTitle), findsWidgets);
expect(find.text(runTitleFieldLabel), findsOneWidget);
expect(_materialFieldText(tester), 'Nightly build');
await tester.enterText(
find.byKey(runTitleFieldKey),
' 发布 🚀 — nightly ',
);
await tester.pump();
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(runTitleCancelKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(gateway.calls, isEmpty);
expect(changed, isEmpty);
expect(
tester.widget<Text>(find.byKey(titleHostTitleKey)).data,
'Nightly build',
);
await tester.tap(find.byKey(runTitleActionKey));
await tester.pumpAndSettle();
expect(_materialFieldText(tester), 'Nightly build');
await tester.enterText(
find.byKey(runTitleFieldKey),
' 发布 🚀 — nightly ',
);
await tester.tap(find.byKey(runTitleSaveKey));
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['set_run_title']);
expect(gateway.calls.single.fields, {
'run_id': 7,
'title': ' 发布 🚀 — nightly ',
});
expect(changed.single, equals(accepted));
expect(find.byType(AlertDialog), findsNothing);
expect(
tester.widget<Text>(find.byKey(titleHostTitleKey)).data,
'Release build',
);
},
);
testWidgets('cupertino rename is native and sends only on Save', (
tester,
) async {
final accepted = renamedRun(title: 'Release build');
final gateway = FakeTitleGateway(
(type, fields) async => {'run_detail': accepted},
);
final changed = <JsonMap>[];
await tester.pumpWidget(
titleApp(
TitleHost(gateway: gateway, initial: titledRun(), changed: changed),
cupertino: true,
),
);
expect(find.byKey(runTitleActionKey), findsOneWidget);
expect(find.byType(CupertinoButton), findsOneWidget);
expect(find.byType(OutlinedButton), findsNothing);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(runTitleActionKey));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
expect(_cupertinoFieldText(tester), 'Nightly build');
await tester.enterText(find.byKey(runTitleFieldKey), 'Typed only');
await tester.pump();
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(runTitleCancelKey));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsNothing);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(runTitleActionKey));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(runTitleFieldKey), 'Release build');
await tester.tap(find.byKey(runTitleSaveKey));
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['set_run_title']);
expect(gateway.calls.single.fields, {
'run_id': 7,
'title': 'Release build',
});
expect(changed.single, equals(accepted));
expect(find.byType(CupertinoAlertDialog), findsNothing);
});
testWidgets('a blank title is sent exactly and the server refusal is shown', (
tester,
) async {
const refusal = 'title must not be blank';
final gateway = FakeTitleGateway(
(type, fields) async => throw const ProtocolError(refusal),
);
final changed = <JsonMap>[];
await tester.pumpWidget(
titleApp(
TitleHost(gateway: gateway, initial: titledRun(), changed: changed),
cupertino: false,
),
);
await tester.tap(find.byKey(runTitleActionKey));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(runTitleFieldKey), '');
await tester.tap(find.byKey(runTitleSaveKey));
await tester.pumpAndSettle();
expect(gateway.calls.single.fields, {'run_id': 7, 'title': ''});
expect(find.text(refusal), findsOneWidget);
expect(find.byKey(runTitleErrorKey), findsOneWidget);
expect(_materialFieldText(tester), '');
expect(find.byType(AlertDialog), findsOneWidget);
expect(changed, isEmpty);
expect(
tester.widget<Text>(find.byKey(titleHostTitleKey)).data,
'Nightly build',
);
expect(
tester.widget<FilledButton>(find.byKey(runTitleSaveKey)).onPressed,
isNotNull,
);
});
testWidgets('the prompt is seeded from the stored title, never the prompt', (
tester,
) async {
final gateway = FakeTitleGateway(
(type, fields) async => {'run_detail': titledRun()},
);
final changed = <JsonMap>[];
await tester.pumpWidget(
titleApp(
TitleHost(
gateway: gateway,
initial: titledRun(
title: 'Stored title',
prompt: 'prompt fallback must not appear',
),
changed: changed,
),
cupertino: false,
),
);
await tester.tap(find.byKey(runTitleActionKey));
await tester.pumpAndSettle();
expect(_materialFieldText(tester), 'Stored title');
expect(find.text('prompt fallback must not appear'), findsNothing);
await tester.tap(find.byKey(runTitleCancelKey));
await tester.pumpAndSettle();
await tester.pumpWidget(
titleApp(
TitleHost(
gateway: gateway,
initial: titledRun(title: null, prompt: 'prompt is not a title'),
changed: changed,
),
cupertino: false,
),
);
await tester.tap(find.byKey(runTitleActionKey));
await tester.pumpAndSettle();
expect(_materialFieldText(tester), '');
expect(find.text('prompt is not a title'), findsNothing);
await tester.tap(find.byKey(runTitleCancelKey));
await tester.pumpAndSettle();
expect(gateway.calls, isEmpty);
expect(changed, isEmpty);
});
testWidgets('a malformed run has no rename entry point', (tester) async {
final gateway = FakeTitleGateway(
(type, fields) async => {'run_detail': titledRun()},
);
await tester.pumpWidget(
titleApp(
TitleHost(
gateway: gateway,
initial: {'title': 'No id'},
changed: <JsonMap>[],
),
cupertino: false,
),
);
expect(find.byKey(runTitleActionKey), findsNothing);
expect(gateway.calls, isEmpty);
expect(runTitleId({'title': 'No id'}), isNull);
expect(storedRunTitle({'title': 'Kept'}), 'Kept');
expect(storedRunTitle({}), '');
});
}
@@ -0,0 +1,243 @@
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/core/transport/connection_state.dart';
import 'package:pipelines_app/features/runs/actions/title_wording.dart';
import 'title_test_support.dart';
Future<void> _pump(
WidgetTester tester,
FakeTitleGateway gateway,
List<JsonMap> changed, {
bool cupertino = false,
double textScale = 1,
JsonMap? run,
}) async {
await tester.pumpWidget(
titleApp(
TitleHost(
gateway: gateway,
initial: run ?? titledRun(),
changed: changed,
),
cupertino: cupertino,
textScale: textScale,
),
);
}
Future<void> _open(WidgetTester tester) async {
await tester.tap(find.byKey(runTitleActionKey));
await tester.pumpAndSettle();
}
String _fieldText(WidgetTester tester, {required bool cupertino}) {
if (cupertino) {
return tester
.widget<CupertinoTextField>(find.byKey(runTitleFieldKey))
.controller!
.text;
}
return tester
.widget<TextField>(find.byKey(runTitleFieldKey))
.controller!
.text;
}
void main() {
testWidgets('a failed save keeps the prompt open with the draft intact', (
tester,
) async {
const refusal = 'rename refused: the run is locked';
final gateway = FakeTitleGateway(
(type, fields) async => throw const ProtocolError(refusal),
);
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _open(tester);
await tester.enterText(find.byKey(runTitleFieldKey), ' Renamed draft ');
await tester.tap(find.byKey(runTitleSaveKey));
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['set_run_title']);
expect(gateway.calls.single.fields, {
'run_id': 7,
'title': ' Renamed draft ',
});
expect(find.text(refusal), findsOneWidget);
expect(find.byKey(runTitleErrorKey), findsOneWidget);
expect(_fieldText(tester, cupertino: false), ' Renamed draft ');
expect(find.byType(AlertDialog), findsOneWidget);
expect(changed, isEmpty);
expect(
tester.widget<Text>(find.byKey(titleHostTitleKey)).data,
'Nightly build',
);
});
testWidgets('a transport failure keeps the server words and the draft', (
tester,
) async {
final gateway = FakeTitleGateway(
(type, fields) async => throw const NotConnectedError(),
);
final changed = <JsonMap>[];
await _pump(tester, gateway, changed, cupertino: true);
await _open(tester);
await tester.enterText(find.byKey(runTitleFieldKey), 'Unsent title');
await tester.tap(find.byKey(runTitleSaveKey));
await tester.pumpAndSettle();
expect(find.byKey(runTitleErrorKey), findsOneWidget);
expect(_fieldText(tester, cupertino: true), 'Unsent title');
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(changed, isEmpty);
});
testWidgets('Save cannot send twice while the rename is in flight', (
tester,
) async {
final reply = Completer<JsonMap>();
final gateway = FakeTitleGateway((type, fields) => reply.future);
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _open(tester);
await tester.enterText(find.byKey(runTitleFieldKey), 'One title');
final save = find.byKey(runTitleSaveKey);
await tester.tap(save);
await tester.tap(save);
await tester.pump();
expect(
gateway.calls.where((call) => call.type == 'set_run_title'),
hasLength(1),
);
expect(tester.widget<FilledButton>(save).onPressed, isNull);
expect(
tester.widget<TextButton>(find.byKey(runTitleCancelKey)).onPressed,
isNull,
);
expect(find.byType(AlertDialog), findsOneWidget);
reply.complete({'run_detail': renamedRun(title: 'One title')});
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(changed, hasLength(1));
expect(changed.single['title'], 'One title');
});
testWidgets('a late reply after disposal is ignored safely', (tester) async {
final reply = Completer<JsonMap>();
final gateway = FakeTitleGateway((type, fields) => reply.future);
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _open(tester);
await tester.tap(find.byKey(runTitleSaveKey));
await tester.pump();
expect(gateway.calls, hasLength(1));
await tester.pumpWidget(const SizedBox());
reply.complete({'run_detail': renamedRun()});
await tester.pump();
expect(tester.takeException(), isNull);
expect(changed, isEmpty);
});
testWidgets('a reply for a run the widget no longer owns is not delivered', (
tester,
) async {
final reply = Completer<JsonMap>();
final gateway = FakeTitleGateway((type, fields) => reply.future);
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _open(tester);
await tester.enterText(find.byKey(runTitleFieldKey), 'Run seven title');
await tester.tap(find.byKey(runTitleSaveKey));
await tester.pump();
await tester.pumpWidget(
titleApp(
TitleHost(
gateway: gateway,
initial: titledRun(id: 8, title: 'Another run'),
changed: changed,
),
cupertino: false,
),
);
await tester.pump();
reply.complete({'run_detail': renamedRun(title: 'Run seven title')});
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(gateway.calls.single.fields, {
'run_id': 7,
'title': 'Run seven title',
});
expect(changed, isEmpty);
expect(
tester.widget<Text>(find.byKey(titleHostTitleKey)).data,
'Another run',
);
});
testWidgets('both prompts fit 2x text at a narrow width', (tester) async {
tester.view.physicalSize = const Size(320, 480);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
const refusal = 'the title is too long for this run; shorten it';
for (final cupertino in [false, true]) {
final gateway = FakeTitleGateway(
(type, fields) async => throw const ProtocolError(refusal),
);
await _pump(
tester,
gateway,
<JsonMap>[],
cupertino: cupertino,
textScale: 2,
);
await _open(tester);
expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino');
expect(
cupertino
? find.byType(CupertinoAlertDialog)
: find.byType(AlertDialog),
findsOneWidget,
);
expect(find.text(runTitleFieldLabel), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.enterText(
find.byKey(runTitleFieldKey),
'A deliberately long title that must scroll rather than overflow',
);
await tester.tap(find.byKey(runTitleSaveKey));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino');
expect(find.text(refusal), findsOneWidget);
expect(
_fieldText(tester, cupertino: cupertino),
'A deliberately long title that must scroll rather than overflow',
);
await tester.tap(find.byKey(runTitleCancelKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(find.byType(CupertinoAlertDialog), findsNothing);
}
});
}
@@ -0,0 +1,110 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/actions/title_action.dart';
typedef TitleHandler = Future<JsonMap> Function(String type, JsonMap fields);
/// A fake gateway that records every request and never owns a socket.
class FakeTitleGateway implements ApiGateway {
FakeTitleGateway(this.handler);
final TitleHandler handler;
final List<({String type, JsonMap fields})> calls = [];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
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();
}
JsonMap titledRun({
num id = 7,
String? title = 'Nightly build',
String status = 'succeeded',
String prompt = 'the submitted prompt',
}) => {
'id': id,
'title': title,
'status': status,
'input': {'prompt': prompt},
};
JsonMap renamedRun({num id = 7, String title = 'Release build'}) =>
titledRun(id: id, title: title, status: 'succeeded');
/// Owns the run like a run-detail screen would, so the callback's returned
/// server detail is what the action renders next. Re-pumping with a different
/// initial run updates the action in place, as a refreshed detail does.
class TitleHost extends StatefulWidget {
const TitleHost({
super.key,
required this.gateway,
required this.initial,
required this.changed,
});
final FakeTitleGateway gateway;
final JsonMap initial;
final List<JsonMap> changed;
@override
State<TitleHost> createState() => _TitleHostState();
}
class _TitleHostState extends State<TitleHost> {
late JsonMap _run = widget.initial;
@override
void didUpdateWidget(covariant TitleHost oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.initial, widget.initial)) {
_run = widget.initial;
}
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('${_run['title'] ?? ''}', key: titleHostTitleKey),
RunTitleAction(
run: _run,
gateway: widget.gateway,
onRunChanged: (run) {
widget.changed.add(run);
setState(() => _run = run);
},
),
],
);
}
}
const titleHostTitleKey = ValueKey<String>('rename-host-title');
Widget titleApp(Widget child, {required bool cupertino, double textScale = 1}) {
Widget media(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: app!,
);
final body = Center(child: child);
if (cupertino) {
return CupertinoApp(
builder: media,
home: CupertinoPageScaffold(child: body),
);
}
return MaterialApp(
builder: media,
home: Scaffold(body: body),
);
}
@@ -0,0 +1,87 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/domain/run_decisions.dart';
import 'package:pipelines_app/features/runs/domain/run_events.dart';
import 'package:pipelines_app/features/runs/domain/run_models.dart';
void main() {
test(
'scheduled origin is immutable and export pending blocks attention/decision',
() {
final rows = <JsonMap>[
{
'id': 5,
'status': 'waiting',
'scheduled': true,
'schedule_id': 12,
'schedule_name': 'Nightly',
},
];
final changed = foldRunEvent(rows, {
'run_id': 5,
'status': 'waiting',
'scheduled': false,
'schedule_id': 99,
'schedule_name': 'Other',
'export_pending_sequence': 4,
});
expect(changed.runs.single['schedule_id'], 12);
expect(changed.runs.single['schedule_name'], 'Nightly');
expect(changed.runs.single['scheduled'], true);
expect(orderAttention(changed.runs), isEmpty);
expect(
pendingDecision({
...changed.runs.single,
'current_stage': 'human',
'steps': [],
}),
isNull,
);
},
);
test(
'pending decision uses recorded options then graph fallback and target labels',
() {
final run = <String, dynamic>{
'id': 7,
'status': 'waiting',
'current_stage': 'human',
'name': 'Build',
'graph': {
'stages': [
{
'key': 'human',
'type': 'human',
'prompt': 'Graph prompt',
'edges': {'go': '#', 'error': '#', 'skip': 'finish'},
},
],
},
'steps': [
{
'sequence': 1,
'status': 'waiting',
'stage': 'human',
'output': {
'prompt': 'Recorded prompt',
'options': ['go'],
},
},
],
};
final decision = pendingDecision(run)!;
expect(decision.instructions, 'Recorded prompt');
expect(decision.options.map((option) => option.key), ['go']);
expect(decision.options.single.target, 'SUCCESS');
final fallback = pendingDecision({
...run,
'steps': [
{'status': 'waiting', 'stage': 'human', 'output': {}},
],
})!;
expect(fallback.instructions, 'Graph prompt');
expect(fallback.options.map((option) => option.key), ['go', 'skip']);
},
);
}
@@ -0,0 +1,189 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/domain/run_events.dart';
void main() {
group('event fold', () {
test('terminal status and resource wait reset are monotonic', () {
final initial = <JsonMap>[
{
'id': 1,
'status': 'succeeded',
'executing': false,
'completed_steps': 4,
},
];
final reset = foldRunEvent(initial, {
'run_id': 1,
'status': 'queued',
'resource_wait_set': true,
'resource_wait': null,
});
expect(reset.runs.single['status'], 'succeeded');
expect(reset.runs.single['executing'], false);
final competing = foldRunEvent(initial, {
'run_id': 1,
'status': 'failed',
'resource_wait_set': true,
});
expect(competing.runs.single['status'], 'succeeded');
expect(competing.runs.single['resource_wait'], isNull);
});
test(
'resource wait reset advances only nonterminal rows, even on stale status',
() {
final rows = <JsonMap>[
{
'id': 2,
'status': 'running',
'executing': true,
'resource_wait': {'resource': 'gpu'},
'completed_steps': 3,
},
];
final result = foldRunEvent(rows, {
'run_id': 2,
'status': 'queued',
'resource_wait_set': true,
'resource_wait': null,
'completed_steps': 1,
});
expect(result.runs.single['status'], 'queued');
expect(result.runs.single['resource_wait'], isNull);
expect(result.runs.single['completed_steps'], 3);
},
);
test(
'new waiting and terminal rows are not executing; identity-less frame resyncs',
() {
for (final status in ['waiting', 'succeeded']) {
final result = foldRunEvent([], {
'run_id': 8,
'pipeline_id': 4,
'name': 'Build',
'status': status,
});
expect(result.runs.single['executing'], false);
}
expect(
foldRunEvent([], {'run_id': 9, 'status': 'running'}).needsResync,
isTrue,
);
},
);
test(
'blank sparse step fields preserve graph evidence and terminal visit',
() {
final detail = <String, dynamic>{
'id': 1,
'status': 'running',
'steps': [
{
'sequence': 2,
'stage': 'review',
'status': 'completed',
'outcome': 'approve',
'target': 'publish',
'diagnostic': 'kept',
},
],
};
final next = foldRunEventDetail(detail, {
'run_id': 1,
'status': 'running',
'step': {
'sequence': 2,
'stage': '',
'status': 'running',
'outcome': ' ',
'target': '',
'diagnostic': '',
},
})!;
final step = (next['steps'] as List).single as JsonMap;
expect(step, containsPair('stage', 'review'));
expect(step, containsPair('status', 'completed'));
expect(step, containsPair('outcome', 'approve'));
expect(step, containsPair('target', 'publish'));
expect(step, containsPair('diagnostic', 'kept'));
},
);
test(
'cancel and cleanup flags stick; resource wait can clear; terminal clears it',
() {
final rows = <JsonMap>[
{
'id': 3,
'status': 'running',
'resource_wait': {'resource': 'gpu'},
},
];
final first = foldRunEvent(rows, {
'run_id': 3,
'status': 'running',
'cancel_requested': true,
'cleanup_unconfirmed': true,
});
final second = foldRunEvent(first.runs, {
'run_id': 3,
'status': 'running',
'cancel_requested': false,
'cleanup_unconfirmed': false,
'resource_wait_set': true,
'resource_wait': null,
});
expect(second.runs.single['cancel_requested'], true);
expect(second.runs.single['cleanup_unconfirmed'], true);
expect(second.runs.single['resource_wait'], isNull);
final terminal = foldRunEvent(second.runs, {
'run_id': 3,
'status': 'failed',
});
expect(terminal.runs.single['resource_wait'], isNull);
},
);
test(
'full sync triggers and list/detail folds agree across stale and current frames',
() {
expect(runDetailNeedsFullSync({'status': 'waiting'}), true);
expect(
runDetailNeedsFullSync({
'status': 'running',
'step': {'status': 'completed'},
}),
true,
);
final summary = <JsonMap>[
{'id': 1, 'status': 'running', 'completed_steps': 1},
];
final frame = {
'run_id': 1,
'status': 'succeeded',
'completed_steps': 2,
'outcome': 'done',
};
final list = foldRunEvent(summary, frame).runs.single;
final detail = foldRunEventDetail({
'id': 1,
'status': 'running',
'completed_steps': 1,
'steps': [],
}, frame)!;
expect(list['status'], detail['status']);
expect(list['completed_steps'], detail['completed_steps']);
final old = foldRunEventDetail(detail, {
'run_id': 1,
'status': 'running',
'outcome': '',
})!;
expect(old['status'], 'succeeded');
expect(old['outcome'], 'done');
},
);
});
}
@@ -0,0 +1,163 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/data/runs_repository.dart';
import 'package:pipelines_app/features/runs/domain/run_models.dart';
class FakeGateway implements ApiGateway {
String? type;
JsonMap fields = {};
JsonMap reply = {};
Object? failure;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
this.type = type;
this.fields = Map.of(fields);
if (failure case final error?) throw error;
return reply;
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
void main() {
test(
'run models match identity, filtering, sorting and null usage behavior',
() {
expect(runIdentity(' Report ', 'Build').label, 'Report');
final rows = <JsonMap>[
{
'id': 1,
'pipeline_id': 2,
'status': 'failed',
'created_at': '2024-01-01T00:00:00Z',
'finished_at': '2024-01-01T00:00:10Z',
},
{
'id': 2,
'pipeline_id': 2,
'status': 'running',
'created_at': '2025-01-01T00:00:00Z',
},
];
expect(filterRuns(rows, statuses: {'failed'}).single['id'], 1);
expect(sortRuns(rows).first['id'], 2);
expect(sortRuns(rows, sort: 'shortest_duration').first['id'], 1);
final scheduled = [
{
'id': 3,
'scheduled': true,
'schedule_id': 9,
'created_at': '2025-03-10T12:00:00Z',
},
{'id': 4, 'scheduled': false, 'created_at': '2025-03-10T12:00:00Z'},
{'id': 5, 'created_at': '2025-03-10T12:00:00Z'},
];
expect(
filterRuns(scheduled, scheduled: 'scheduled').map((run) => run['id']),
[3],
);
expect(
filterRuns(
scheduled,
scheduled: 'unscheduled',
timeRange: 'today',
today: DateTime(2025, 3, 10),
).map((run) => run['id']),
[4],
);
expect(
runStatusLabel({'status': 'waiting', 'export_pending_sequence': 2}),
'Waiting for session export',
);
expect(RunListResult(const [], null).usage, isNull);
},
);
test('repository sends exact action and launch requests', () async {
final gateway = FakeGateway()
..reply = {
'run_detail': {'id': 3},
};
final repo = RunsRepository(gateway);
gateway.reply = {
'runs': [
{'id': 1, 'status': 'running'},
],
'usage': {'active': 1},
};
final listed = await repo.listRuns();
expect(gateway.type, 'list_runs');
expect(gateway.fields, isEmpty);
expect(listed.runs.single['id'], 1);
expect(listed.usage, {'active': 1});
gateway.reply = {
'run_detail': {'id': 3},
};
await repo.retryRun(3, requestKey: 'retry-1');
expect(gateway.type, 'retry_run');
expect(gateway.fields, {'run_id': 3, 'request_key': 'retry-1'});
await repo.retryRun(3, requestKey: 'retry-2', mode: 'restart');
expect(gateway.fields, {
'run_id': 3,
'request_key': 'retry-2',
'retry_mode': 'restart',
});
await repo.decideRun(3, stage: 'human', option: ' go ', feedback: ' yes ');
expect(gateway.fields, {
'run_id': 3,
'stage': 'human',
'option': 'go',
'feedback': 'yes',
});
await repo.cancelRun(3);
expect(gateway.type, 'cancel_run');
expect(gateway.fields, {'run_id': 3});
await repo.setRunTitle(3, 'New');
expect(gateway.type, 'set_run_title');
expect(gateway.fields, {'run_id': 3, 'title': 'New'});
await repo.startRun(
pipelineId: 4,
version: 2,
prompt: 'hello',
workspace: ' /work ',
requestKey: 'start-2',
title: ' Job ',
notifyMode: 'off',
outputFormat: 'json',
);
expect(gateway.type, 'run_pipeline');
expect(gateway.fields, {
'pipeline_id': 4,
'version': 2,
'request_key': 'start-2',
'workspace': '/work',
'input': {'prompt': 'hello'},
'title': 'Job',
'notify_mode': 'off',
'output_format': 'json',
});
});
test(
'repository propagates server refusals and rejects missing detail',
() async {
final gateway = FakeGateway()..reply = {};
final repo = RunsRepository(gateway);
await expectLater(
repo.getRun(3),
throwsA(isA<RunsRepositoryException>()),
);
await expectLater(
repo.decideRun(3, option: ' '),
throwsA(isA<RunsRepositoryException>()),
);
gateway.failure = const RunsRepositoryException('server refused');
await expectLater(
repo.cancelRun(3),
throwsA(predicate((error) => '$error' == 'server refused')),
);
},
);
}
@@ -0,0 +1,264 @@
import 'dart:async';
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/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';
enum AppPlatform { material, cupertino }
class FakeGateway implements ApiGateway {
FakeGateway(this.detail);
JsonMap detail;
Object? failure;
Completer<JsonMap>? hold;
@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);
if (hold != null) return hold!.future;
if (failure != null) return Future.error(failure!);
return Future.value({'run_detail': detail});
}
}
const prompt = ' keep\n\nspacing ';
JsonMap runFixture({JsonMap? usage, int steps = 2}) {
final run = <String, dynamic>{
'id': 7,
'title': 'Nightly build',
'name': 'release',
'status': 'succeeded',
'input': {
'prompt': prompt,
'nested': {
'alpha': 1,
'items': [1, 2],
},
},
'output': {
'result': {'ok': true},
},
'steps': [
for (var i = 0; i < steps; i++)
{
'stage': i == 0 ? 'build' : 'test',
'sequence': i + 3,
'status': 'completed',
'outcome': 'success',
'target': '#success',
},
],
};
if (usage != null) run['usage'] = usage;
return run;
}
JsonMap usageFixture({int known = 1}) => {
'stages': 1,
'tokens_total': 0,
'tokens_known_stages': known,
'tokens_in': 0,
'tokens_out': 0,
'split_known': true,
'cost_known_stages': known,
};
Future<void> pumpDetail(
WidgetTester tester,
AppPlatform platform,
RunsController controller, {
VoidCallback? onBack,
bool settle = true,
}) async {
tester.view.physicalSize = const Size(390, 1600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final view = RunDetailView(controller: controller, onBack: onBack ?? () {});
final page = MediaQuery(
data: MediaQueryData.fromView(
tester.view,
).copyWith(textScaler: const TextScaler.linear(2)),
child: view,
);
await tester.pumpWidget(
platform == AppPlatform.material
? MaterialApp(home: Scaffold(body: page))
: CupertinoApp(
home: CupertinoPageScaffold(child: SafeArea(child: page)),
),
);
if (settle) {
await tester.pumpAndSettle();
} else {
await tester.pump();
}
}
void mockClipboard(
WidgetTester tester,
List<String> copied, {
bool Function()? denied,
}) {
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
if (call.method != 'Clipboard.setData') return null;
if (denied?.call() ?? false) {
throw PlatformException(code: 'clipboard-denied');
}
copied.add((call.arguments as Map)['text'] as String);
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
}
void main() {
late FakeGateway gateway;
late RunsController controller;
setUp(() {
gateway = FakeGateway(runFixture());
controller = RunsController(RunsRepository(gateway));
});
tearDown(() => controller.dispose());
for (final platform in AppPlatform.values) {
testWidgets('${platform.name} detail at 390 with 2x text', (tester) async {
gateway.detail = runFixture(steps: 12);
await controller.select(1);
await pumpDetail(tester, platform, controller);
expect(tester.takeException(), isNull);
expect(find.text('Nightly build'), findsOneWidget);
expect(find.textContaining('Original prompt'), findsOneWidget);
if (platform == AppPlatform.material) {
expect(find.byType(Chip), findsOneWidget);
expect(find.byType(ExpansionTile), findsNWidgets(2));
} else {
expect(find.byType(Material), findsNothing);
expect(find.byType(Chip), findsNothing);
expect(find.byType(CupertinoExpansionTile), findsNWidgets(2));
}
await tester.tap(find.text('Input'));
await tester.pumpAndSettle();
expect(find.textContaining('"alpha": 1'), findsOneWidget);
await tester.scrollUntilVisible(
find.text('Output'),
200,
scrollable: find.byType(Scrollable).first,
);
await tester.tap(find.text('Output'));
await tester.pumpAndSettle();
expect(find.textContaining('"ok": true'), findsOneWidget);
await tester.scrollUntilVisible(
find.textContaining('build · visit 3'),
200,
scrollable: find.byType(Scrollable).first,
);
expect(find.textContaining('build · visit 3'), findsOneWidget);
expect(find.textContaining('test · visit 4'), findsOneWidget);
if (platform == AppPlatform.material) {
final scrollable = tester.state<ScrollableState>(
find.byType(Scrollable).first,
);
final before = scrollable.position.pixels;
expect(before, greaterThan(0));
gateway.detail = runFixture(steps: 13);
await controller.select(1);
await tester.pumpAndSettle();
expect(scrollable.position.pixels, closeTo(before, 0.1));
}
});
testWidgets('${platform.name} loading and error stay honest', (
tester,
) async {
gateway.hold = Completer<JsonMap>();
final pending = controller.select(1);
await pumpDetail(tester, platform, controller, settle: false);
expect(find.text('Loading run details…'), findsOneWidget);
expect(
find.byType(
platform == AppPlatform.material
? CircularProgressIndicator
: CupertinoActivityIndicator,
),
findsOneWidget,
);
gateway.hold!.complete({'run_detail': runFixture()});
await pending;
await tester.pumpAndSettle();
expect(find.text('Nightly build'), findsOneWidget);
controller.dispose();
gateway = FakeGateway(runFixture())
..failure = StateError('server unavailable');
controller = RunsController(RunsRepository(gateway));
await controller.select(1);
var backs = 0;
await pumpDetail(tester, platform, controller, onBack: () => backs++);
expect(find.textContaining('server unavailable'), findsOneWidget);
await tester.tap(find.text('Back to list'));
expect(backs, 1);
});
testWidgets('${platform.name} copies the exact prompt and reports denial', (
tester,
) async {
final copied = <String>[];
var denied = false;
mockClipboard(tester, copied, denied: () => denied);
final copy = platform == AppPlatform.material
? find.byTooltip('Copy prompt')
: find.text('Copy prompt');
await controller.select(1);
await pumpDetail(tester, platform, controller);
await tester.tap(copy);
await tester.pumpAndSettle();
expect(copied.single, prompt);
expect(find.text('Prompt copied to clipboard.'), findsOneWidget);
if (platform == AppPlatform.material) {
await tester.pump(const Duration(seconds: 5));
await tester.pumpAndSettle();
}
denied = true;
await tester.tap(copy);
await tester.pumpAndSettle();
expect(find.text('Could not copy prompt to clipboard.'), findsOneWidget);
});
}
testWidgets('reported zero and missing usage stay distinct', (tester) async {
gateway.detail = runFixture(usage: usageFixture());
await controller.select(1);
await pumpDetail(tester, AppPlatform.material, controller);
await tester.tap(find.text('Metrics'));
await tester.pumpAndSettle();
expect(find.text('Unavailable'), findsNothing);
expect(find.text('0'), findsNWidgets(3));
expect(find.text('\$0.000000'), findsOneWidget);
gateway.detail = runFixture(usage: usageFixture(known: 0));
await controller.select(1);
await tester.pumpAndSettle();
expect(find.text('Unavailable'), findsNWidgets(4));
expect(find.text('0'), findsNothing);
});
}
@@ -0,0 +1,344 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/data/runs_repository.dart';
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
class FakeGateway implements ApiGateway {
final framesController = StreamController<JsonMap>.broadcast();
final lists = <Completer<JsonMap>>[];
final details = <num, List<Completer<JsonMap>>>{};
int listCalls = 0;
@override
Stream<JsonMap> get frames => framesController.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type == 'list_runs') {
listCalls++;
final request = Completer<JsonMap>();
lists.add(request);
return request.future;
}
final id = fields['run_id'] as num;
final request = Completer<JsonMap>();
details.putIfAbsent(id, () => []).add(request);
return request.future;
}
void listReply(int index, List<JsonMap> runs) =>
lists[index].complete({'runs': runs});
void detailReply(num id, int index, JsonMap value) =>
details[id]![index].complete({'run_detail': value});
}
void main() {
late FakeGateway gateway;
late RunsController controller;
var disposed = false;
setUp(() {
gateway = FakeGateway();
controller = RunsController(RunsRepository(gateway));
disposed = false;
});
tearDown(() {
if (!disposed) controller.dispose();
gateway.framesController.close();
});
test('late selection response cannot replace latest selection', () async {
final first = controller.select(1);
final second = controller.select(2);
gateway.detailReply(2, 0, {'id': 2});
await second;
gateway.detailReply(1, 0, {'id': 1});
await first;
expect(controller.detail?['id'], 2);
});
test('pending load and selection futures are safe after dispose', () async {
final load = controller.load();
final select = controller.select(1);
controller.dispose();
disposed = true;
gateway.listReply(0, []);
gateway.detailReply(1, 0, {'id': 1});
await Future.wait([load, select]);
});
test('Back cancels scheduled detail refresh', () async {
final select = controller.select(1);
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
await select;
controller.listen(gateway.frames);
gateway.framesController.add({
'type': 'run_event',
'run_id': 1,
'status': 'succeeded',
});
controller.back();
await Future<void>.delayed(const Duration(milliseconds: 220));
expect(gateway.details[1], hasLength(1));
expect(controller.detail, isNull);
});
test('unrelated run event does not refresh selected detail', () async {
final select = controller.select(1);
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
await select;
controller.listen(gateway.frames);
gateway.framesController.add({
'type': 'run_event',
'run_id': 2,
'status': 'succeeded',
});
await Future<void>.delayed(const Duration(milliseconds: 220));
expect(gateway.details[1], hasLength(1));
});
test('identity-less event reloads list', () async {
controller.listen(gateway.frames);
gateway.framesController.add({'type': 'run_event', 'status': 'running'});
await Future<void>.delayed(Duration.zero);
expect(gateway.listCalls, 1);
gateway.listReply(0, [
{'id': 3},
]);
await Future<void>.delayed(Duration.zero);
expect(controller.runs.single['id'], 3);
expect(controller.loading, isFalse);
});
test(
'full refresh is coalesced and keeps current detail until reply',
() async {
final select = controller.select(1);
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
await select;
controller.listen(gateway.frames);
gateway.framesController.add({
'type': 'run_event',
'run_id': 1,
'status': 'succeeded',
});
await Future<void>.delayed(const Duration(milliseconds: 180));
expect(controller.detail?['id'], 1);
expect(gateway.details[1], hasLength(2));
gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'});
await Future<void>.delayed(Duration.zero);
expect(controller.detail?['status'], 'succeeded');
},
);
test('load with initial id clears list and detail loading', () async {
final load = controller.load(7);
expect(controller.loading, isTrue);
gateway.listReply(0, [
{'id': 7},
{'id': 8},
]);
await Future<void>.delayed(Duration.zero);
expect(gateway.details[7], hasLength(1));
expect(controller.loading, isFalse);
expect(controller.detailLoading, isTrue);
gateway.detailReply(7, 0, {'id': 7});
await load;
expect(controller.loading, isFalse);
expect(controller.detailLoading, isFalse);
expect(controller.detail?['id'], 7);
expect(controller.selectedRunId, 7);
});
test('newer list load wins when replies complete out of order', () async {
final first = controller.load();
final second = controller.load();
gateway.listReply(1, [
{'id': 2},
]);
await second;
gateway.listReply(0, [
{'id': 1},
]);
await first;
expect(controller.runs.single['id'], 2);
expect(controller.loading, isFalse);
});
test('list resync leaves the selected detail request valid', () async {
final select = controller.select(1);
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
await select;
controller.listen(gateway.frames);
gateway.framesController.add({'type': 'run_event', 'status': 'running'});
await Future<void>.delayed(Duration.zero);
expect(gateway.listCalls, 1);
gateway.listReply(0, [
{'id': 1, 'status': 'running'},
]);
await Future<void>.delayed(Duration.zero);
expect(controller.detail?['id'], 1);
expect(controller.selectedRunId, 1);
expect(gateway.details[1], hasLength(1));
});
test('manual list load keeps an in-flight detail refresh valid', () async {
final select = controller.select(1);
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
await select;
controller.listen(gateway.frames);
gateway.framesController.add({
'type': 'run_event',
'run_id': 1,
'status': 'succeeded',
});
await Future<void>.delayed(const Duration(milliseconds: 180));
expect(gateway.details[1], hasLength(2));
final load = controller.load();
gateway.listReply(1, [
{'id': 1},
]);
await load;
gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'});
await Future<void>.delayed(Duration.zero);
expect(controller.detail?['status'], 'succeeded');
expect(controller.detailLoading, isFalse);
gateway.listReply(0, [
{'id': 1},
]);
});
test('event during a superseded resync still runs one followup', () async {
controller.listen(gateway.frames);
gateway.framesController.add({
'type': 'run_event',
'run_id': 9,
'status': 'running',
});
await Future<void>.delayed(Duration.zero);
expect(gateway.listCalls, 1);
final load = controller.load();
expect(gateway.listCalls, 2);
gateway.listReply(1, [
{'id': 1},
]);
await load;
gateway.framesController.add({
'type': 'run_event',
'run_id': 10,
'status': 'running',
});
await Future<void>.delayed(Duration.zero);
expect(gateway.listCalls, 2);
gateway.listReply(0, [
{'id': 1},
]);
await Future<void>.delayed(Duration.zero);
expect(gateway.listCalls, 3);
gateway.listReply(2, [
{'id': 1},
{'id': 2},
]);
await Future<void>.delayed(Duration.zero);
expect(controller.runs, hasLength(2));
expect(controller.loading, isFalse);
});
test('unknown run events coalesce into one followup resync', () async {
controller.listen(gateway.frames);
gateway.framesController.add({
'type': 'run_event',
'run_id': 9,
'status': 'running',
});
await Future<void>.delayed(Duration.zero);
expect(gateway.listCalls, 1);
expect(controller.loading, isTrue);
gateway.framesController.add({
'type': 'run_event',
'run_id': 10,
'status': 'running',
});
await Future<void>.delayed(Duration.zero);
expect(gateway.listCalls, 1);
gateway.listReply(0, [
{'id': 3},
]);
await Future<void>.delayed(Duration.zero);
expect(gateway.listCalls, 2);
expect(controller.loading, isTrue);
gateway.listReply(1, [
{'id': 3},
{'id': 4},
]);
await Future<void>.delayed(Duration.zero);
expect(gateway.listCalls, 2);
expect(controller.loading, isFalse);
expect(controller.runs, hasLength(2));
});
test(
'selected refresh coalesces and Back ignores the pending reply',
() async {
final select = controller.select(1);
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
await select;
controller.listen(gateway.frames);
gateway.framesController.add({
'type': 'run_event',
'run_id': 1,
'status': 'succeeded',
});
await Future<void>.delayed(const Duration(milliseconds: 180));
expect(gateway.details[1], hasLength(2));
gateway.framesController.add({
'type': 'run_event',
'run_id': 1,
'status': 'failed',
});
await Future<void>.delayed(Duration.zero);
expect(gateway.details[1], hasLength(2));
gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'});
await Future<void>.delayed(Duration.zero);
expect(gateway.details[1], hasLength(3));
controller.back();
gateway.detailReply(1, 2, {'id': 1, 'status': 'failed'});
await Future<void>.delayed(Duration.zero);
expect(controller.detail, isNull);
expect(controller.detailLoading, isFalse);
expect(controller.error, isNull);
},
);
test('choosing another run does not display the previous detail', () async {
final first = controller.select(1);
gateway.detailReply(1, 0, {'id': 1});
await first;
final second = controller.select(2);
expect(controller.detail, isNull);
expect(controller.selectedRunId, 2);
expect(controller.detailLoading, isTrue);
gateway.detailReply(2, 0, {'id': 2});
await second;
expect(controller.detail?['id'], 2);
expect(controller.detailLoading, isFalse);
});
test('pending detail refresh is safe after dispose', () async {
final select = controller.select(1);
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
await select;
controller.listen(gateway.frames);
gateway.framesController.add({
'type': 'run_event',
'run_id': 1,
'status': 'succeeded',
});
await Future<void>.delayed(const Duration(milliseconds: 180));
expect(gateway.details[1], hasLength(2));
controller.dispose();
disposed = true;
gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'});
await Future<void>.delayed(Duration.zero);
expect(controller.detail?['id'], 1);
});
}
@@ -0,0 +1,180 @@
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/data/runs_repository.dart';
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
import 'package:pipelines_app/features/runs/ui/runs_list.dart';
class _Gateway implements ApiGateway {
final framesController = StreamController<JsonMap>.broadcast();
JsonMap? reply;
Object? failure;
Completer<void>? gate;
@override
Stream<JsonMap> get frames => framesController.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
await gate?.future;
if (failure != null) throw failure!;
return reply ?? {'runs': []};
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late _Gateway gateway;
late RunsController controller;
setUp(() {
gateway = _Gateway();
controller = RunsController(RunsRepository(gateway));
});
tearDown(() async {
controller.dispose();
await gateway.framesController.close();
});
Future<void> mount(
WidgetTester tester, {
required bool cupertino,
ValueChanged<num>? onSelected,
}) async {
gateway.reply = {
'runs': [
{'id': 1, 'name': 'Alpha', 'status': 'running', 'scheduled': true},
{'id': 2, 'name': 'Beta', 'status': 'failed', 'scheduled': false},
],
};
await controller.load();
final list = AnimatedBuilder(
animation: controller,
builder: (context, _) =>
RunsList(controller: controller, onSelected: onSelected ?? (_) {}),
);
await tester.pumpWidget(
cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: list))
: MaterialApp(home: Scaffold(body: list)),
);
}
testWidgets(
'uses native search and filters runs in CupertinoApp',
(tester) async {
num? selectedRun;
await mount(
tester,
cupertino: true,
onSelected: (id) => selectedRun = id,
);
expect(find.byType(CupertinoSearchTextField), findsOneWidget);
expect(find.text('Alpha'), findsOneWidget);
await tester.enterText(find.byType(CupertinoSearchTextField), 'Beta');
await tester.pumpAndSettle();
expect(find.text('Beta'), findsNWidgets(2));
expect(find.text('Alpha'), findsNothing);
await tester.tap(find.byType(CupertinoListTile));
expect(selectedRun, 2);
await tester.enterText(find.byType(CupertinoSearchTextField), 'missing');
await tester.pumpAndSettle();
expect(find.text('No runs found.'), findsOneWidget);
await tester.enterText(find.byType(CupertinoSearchTextField), '');
await tester.pumpAndSettle();
await tester.tap(find.textContaining('Schedule:'));
await tester.pumpAndSettle();
expect(find.text('Scheduled'), findsWidgets);
await tester.tap(find.text('Scheduled').last);
await tester.pumpAndSettle();
expect(controller.scheduled, 'scheduled');
},
variant: TargetPlatformVariant.only(TargetPlatform.iOS),
);
testWidgets(
'retains Material controls and handles large text on narrow layout',
(tester) async {
tester.view.devicePixelRatio = 2;
tester.view.physicalSize = const Size(780, 1560);
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: const TextScaler.linear(2)),
child: child!,
),
home: Scaffold(
body: AnimatedBuilder(
animation: controller,
builder: (_, _) =>
RunsList(controller: controller, onSelected: (_) {}),
),
),
),
);
gateway.reply = {
'runs': [
{'id': 1, 'name': 'Alpha', 'status': 'running', 'scheduled': true},
{'id': 2, 'name': 'Beta', 'status': 'failed', 'scheduled': false},
],
};
await controller.load();
await tester.pumpAndSettle();
expect(find.byType(TextField), findsOneWidget);
final layoutError = tester.takeException();
expect(
layoutError,
isNull,
reason: layoutError is FlutterError
? layoutError.toStringDeep()
: '$layoutError',
);
},
variant: TargetPlatformVariant.only(TargetPlatform.android),
);
testWidgets(
'shows loading, error and server-empty states distinctly',
(tester) async {
gateway.failure = StateError('offline');
gateway.gate = Completer<void>();
final loading = controller.load();
await tester.pumpWidget(
CupertinoApp(
home: CupertinoPageScaffold(
child: AnimatedBuilder(
animation: controller,
builder: (_, child) =>
RunsList(controller: controller, onSelected: (_) {}),
),
),
),
);
await tester.pump();
expect(find.byType(CupertinoActivityIndicator), findsOneWidget);
gateway.gate!.complete();
await loading;
await tester.pumpAndSettle();
expect(find.textContaining('offline'), findsOneWidget);
expect(tester.takeException(), isNull);
gateway.failure = null;
gateway.gate = null;
gateway.reply = {'runs': []};
await controller.load();
await tester.pumpAndSettle();
expect(find.text('No runs found.'), findsOneWidget);
expect(find.textContaining('offline'), findsNothing);
expect(tester.takeException(), isNull);
},
variant: TargetPlatformVariant.only(TargetPlatform.iOS),
);
}
@@ -0,0 +1,247 @@
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/screen.dart';
class _Gateway implements ApiGateway {
final framesController = StreamController<JsonMap>.broadcast();
final listRequests = <Completer<JsonMap>>[];
final detailRequests = <num, List<Completer<JsonMap>>>{};
@override
Stream<JsonMap> get frames => framesController.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
final request = Completer<JsonMap>();
if (type == 'list_runs') {
listRequests.add(request);
} else if (type == 'get_run') {
final id = fields['run_id'] as num;
detailRequests.putIfAbsent(id, () => []).add(request);
} else {
request.completeError(UnsupportedError(type));
}
return request.future;
}
void replyList(int index, List<JsonMap> runs) =>
listRequests[index].complete({'runs': runs});
void replyDetail(num id, int index, JsonMap detail) =>
detailRequests[id]![index].complete({'run_detail': detail});
void failDetail(num id, int index, Object error) =>
detailRequests[id]![index].completeError(error);
}
const _runs = [
{'id': 1, 'title': 'Alpha run', 'name': 'alpha', 'status': 'running'},
{'id': 2, 'title': 'Beta run', 'name': 'beta', 'status': 'failed'},
];
Widget _materialScreen(
_Gateway gateway, {
int? initialRunId,
int syncToken = 0,
ValueChanged<int>? onRunSelected,
VoidCallback? onBack,
}) => MaterialApp(
home: Scaffold(
body: RunsScreen(
gateway: gateway,
initialRunId: initialRunId,
syncToken: syncToken,
onRunSelected: onRunSelected,
onBack: onBack,
),
),
);
Future<void> _mountList(WidgetTester tester, _Gateway gateway) async {
await tester.pump();
gateway.replyList(0, _runs);
await tester.pump();
await tester.pump();
}
void main() {
late _Gateway gateway;
setUp(() => gateway = _Gateway());
tearDown(() => gateway.framesController.close());
testWidgets('initial run opens a pending detail with Back available', (
tester,
) async {
await tester.pumpWidget(_materialScreen(gateway, initialRunId: 1));
await _mountList(tester, gateway);
expect(gateway.detailRequests[1], hasLength(1));
expect(find.text('Loading run details…'), findsOneWidget);
expect(find.text('Back to list'), findsOneWidget);
expect(find.text('Alpha run'), findsNothing);
await tester.tap(find.text('Back to list'));
await tester.pump();
expect(find.text('Alpha run'), findsOneWidget);
expect(find.text('Beta run'), findsOneWidget);
// A reply that lands after Back must not reopen the previous detail.
gateway.replyDetail(1, 0, {'id': 1, 'title': 'Alpha run'});
await tester.pump();
expect(find.text('Alpha run'), findsOneWidget);
expect(find.text('Loading run details…'), findsNothing);
});
testWidgets('initial run renders its detail after the reply', (tester) async {
await tester.pumpWidget(_materialScreen(gateway, initialRunId: 1));
await _mountList(tester, gateway);
gateway.replyDetail(1, 0, {
'id': 1,
'title': 'Alpha run',
'status': 'succeeded',
'input': {'prompt': 'initial prompt'},
});
await tester.pump();
expect(find.text('Alpha run'), findsOneWidget);
expect(find.text('initial prompt'), findsOneWidget);
expect(find.text('Loading run details…'), findsNothing);
});
testWidgets('detail failure keeps Back and returns to the list', (
tester,
) async {
await tester.pumpWidget(_materialScreen(gateway, initialRunId: 2));
await _mountList(tester, gateway);
gateway.failDetail(2, 0, StateError('server unavailable'));
await tester.pump();
expect(find.textContaining('server unavailable'), findsOneWidget);
expect(find.text('Back to list'), findsOneWidget);
await tester.tap(find.text('Back to list'));
await tester.pump();
expect(find.text('Alpha run'), findsOneWidget);
expect(find.textContaining('server unavailable'), findsNothing);
});
testWidgets('selecting a list row is driven by the controller selection', (
tester,
) async {
await tester.pumpWidget(_materialScreen(gateway));
await _mountList(tester, gateway);
await tester.tap(find.text('Beta run'));
await tester.pump();
expect(gateway.detailRequests[2], hasLength(1));
gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'});
await tester.pump();
expect(find.text('Beta run'), findsOneWidget);
expect(find.text('Back to list'), findsOneWidget);
});
testWidgets('selection and Back report route changes to the host', (
tester,
) async {
int? selected;
var backs = 0;
await tester.pumpWidget(
_materialScreen(
gateway,
onRunSelected: (id) => selected = id,
onBack: () => backs++,
),
);
await _mountList(tester, gateway);
await tester.tap(find.text('Beta run'));
await tester.pump();
expect(selected, 2);
gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'});
await tester.pump();
await tester.tap(find.text('Back to list'));
await tester.pump();
expect(backs, 1);
expect(find.text('Alpha run'), findsOneWidget);
});
testWidgets('a route change opens and closes the named run', (tester) async {
await tester.pumpWidget(_materialScreen(gateway, initialRunId: 2));
await _mountList(tester, gateway);
expect(gateway.detailRequests[2], hasLength(1));
gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'});
await tester.pump();
expect(find.text('Beta run'), findsOneWidget);
await tester.pumpWidget(_materialScreen(gateway, initialRunId: 1));
await tester.pump();
expect(gateway.detailRequests[1], hasLength(1));
gateway.replyDetail(1, 0, {'id': 1, 'title': 'Alpha run'});
await tester.pump();
expect(find.text('Alpha run'), findsOneWidget);
await tester.pumpWidget(_materialScreen(gateway));
await tester.pump();
expect(find.text('Alpha run'), findsOneWidget);
expect(find.text('Beta run'), findsOneWidget);
expect(find.text('Back to list'), findsNothing);
});
testWidgets('a reconnect token refreshes the open detail in place', (
tester,
) async {
await tester.pumpWidget(_materialScreen(gateway, initialRunId: 2));
await _mountList(tester, gateway);
gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'});
await tester.pump();
expect(find.text('Beta run'), findsOneWidget);
await tester.pumpWidget(
_materialScreen(gateway, initialRunId: 2, syncToken: 1),
);
await tester.pump();
expect(gateway.listRequests, hasLength(2));
gateway.replyList(1, _runs);
await tester.pump();
await tester.pump();
expect(gateway.detailRequests[2], hasLength(2));
gateway.replyDetail(2, 1, {
'id': 2,
'title': 'Beta run',
'status': 'succeeded',
});
await tester.pump();
expect(find.text('Beta run'), findsOneWidget);
expect(find.text('Back to list'), findsOneWidget);
});
testWidgets(
'Cupertino host keeps exactly one navigation bar while pending',
(tester) async {
await tester.pumpWidget(
CupertinoApp(
home: CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: Text('Runs')),
child: SafeArea(
child: RunsScreen(gateway: gateway, initialRunId: 1),
),
),
),
);
await _mountList(tester, gateway);
expect(find.byType(CupertinoPageScaffold), findsOneWidget);
expect(find.byType(CupertinoNavigationBar), findsOneWidget);
expect(find.text('Loading run details…'), findsOneWidget);
expect(find.byType(CupertinoActivityIndicator), findsOneWidget);
expect(find.text('Back to list'), findsOneWidget);
},
variant: TargetPlatformVariant.only(TargetPlatform.iOS),
);
}
@@ -0,0 +1,101 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart';
import 'schedule_test_support.dart';
void main() {
test('saved schedule exposes run-configuration provenance', () {
final schedule = SavedSchedule(savedRecord());
expect(schedule.id, 8);
expect(schedule.revision, 3);
expect(schedule.pipelineId, 4);
expect(schedule.version, 2);
expect(schedule.name, 'Research batteries');
expect(schedule.enabled, isTrue);
expect(schedule.prompt, 'Research batteries');
expect(schedule.input['custom'], {'nested': 'kept'});
expect(schedule.workspace, '/srv/research');
expect(schedule.writePaths, ['reports/research.md']);
expect(schedule.allowTools, isTrue);
expect(schedule.model, 'openai/gpt-5');
expect(schedule.stageModels, {'one': 'openai/gpt-5'});
expect(schedule.notifyMode, 'off');
expect(schedule.title, 'Battery research');
expect(schedule.outputFormat, 'markdown');
expect(schedule.rule.every, '24h');
expect(schedule.rule.days, ['mon', 'wed']);
expect(schedule.rule.timezone, 'Europe/London');
expect(schedule.rule.isClock, isFalse);
expect(schedule.nextDue, '2026-10-22T09:00:00Z');
expect(schedule.createdAt, '2026-10-20T09:00:00Z');
expect(schedule.updatedAt, '2026-10-21T09:00:00Z');
});
test('unknown fields survive the typed view and pause copy', () {
final schedule = SavedSchedule(savedRecord());
final paused = schedule.withEnabled(false);
expect(paused.enabled, isFalse);
expect(paused.id, 8);
expect(paused.revision, 3);
expect(paused.toJson()['future_server_field'], {
'nested': [
1,
2,
{'deep': true},
],
});
expect(paused.toJson()['input'], {
'prompt': 'Research batteries',
'custom': {'nested': 'kept'},
});
expect(paused.toJson()['rule'], savedRecord()['rule']);
// The original snapshot is untouched and still enabled.
expect(schedule.enabled, isTrue);
expect(schedule.revision, 3);
});
test('toJson is a deep copy, not an alias of the server reply', () {
final source = savedRecord();
final schedule = SavedSchedule(source);
final first = schedule.toJson();
((first['future_server_field'] as Map)['nested'] as List).add('changed');
final second = schedule.toJson();
expect((second['future_server_field'] as Map)['nested'], [
1,
2,
{'deep': true},
]);
final promptInput = schedule.input;
promptInput['custom'] = 'changed';
expect(schedule.input['custom'], {'nested': 'kept'});
});
test('missing fields stay absent instead of being fabricated', () {
final schedule = SavedSchedule(const {});
expect(schedule.id, isNull);
expect(schedule.revision, isNull);
expect(schedule.pipelineId, isNull);
expect(schedule.version, isNull);
expect(schedule.enabled, isFalse);
expect(schedule.prompt, '');
expect(schedule.workspace, '');
expect(schedule.rule.every, '');
expect(schedule.rule.times, isEmpty);
expect(schedule.writePaths, isEmpty);
expect(schedule.stageModels, isEmpty);
expect(schedule.toJson(), isEmpty);
});
test('a fractional revision is not truncated into a false token', () {
final schedule = SavedSchedule(const {'id': 8, 'revision': 3.5});
expect(schedule.id, 8);
expect(schedule.revision, isNull);
});
}
@@ -0,0 +1,83 @@
import 'dart:convert';
import 'package:pipelines_app/core/api_gateway.dart';
class RecordedCall {
const RecordedCall(this.type, this.fields);
final String type;
final JsonMap fields;
}
/// Records the exact request built by the repository and replays queued
/// replies. Both are deep-copied, so a test can prove the repository neither
/// mutated its input nor depended on alias mutation of a reply.
class RecordingGateway implements ApiGateway {
final calls = <RecordedCall>[];
final replies = <JsonMap>[];
Object? failure;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(RecordedCall(type, deepCopy(fields)));
if (failure case final error?) throw error;
if (replies.isEmpty) throw StateError('No recorded reply for $type');
return deepCopy(replies.removeAt(0));
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
JsonMap deepCopy(JsonMap value) => jsonDecode(jsonEncode(value)) as JsonMap;
/// A complete server record including fields this client does not interpret
/// yet, an unknown nested rule field and unknown input.
JsonMap savedRecord() => {
'id': 8,
'revision': 3,
'name': 'Research batteries',
'pipeline_id': 4,
'version': 2,
'enabled': true,
'input': {
'prompt': 'Research batteries',
'custom': {'nested': 'kept'},
},
'workspace': '/srv/research',
'write_paths': ['reports/research.md'],
'allow_tools': true,
'model': 'openai/gpt-5',
'stage_models': {'one': 'openai/gpt-5'},
'notify_mode': 'off',
'title': 'Battery research',
'output_format': 'markdown',
'rule': {
'every': '24h',
'days': ['mon', 'wed'],
'timezone': 'Europe/London',
'future_rule_field': 'kept',
},
'next_due': '2026-10-22T09:00:00Z',
'created_at': '2026-10-20T09:00:00Z',
'updated_at': '2026-10-21T09:00:00Z',
'future_server_field': {
'nested': [
1,
2,
{'deep': true},
],
},
};
/// The create form of the record: id 0 is the server's create sentinel and no
/// revision has been issued yet.
JsonMap createRecord() => {
'id': 0,
'name': 'Research batteries',
'pipeline_id': 4,
'version': 2,
'enabled': true,
'input': {'prompt': 'Research batteries'},
'workspace': '/srv/research',
'rule': {'every': '24h', 'timezone': 'Europe/London'},
};
@@ -0,0 +1,131 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'package:pipelines_app/features/schedules/data/schedules_repository.dart';
import 'schedule_test_support.dart';
void main() {
test('delete sends the exact ID and expected revision', () async {
final gateway = RecordingGateway()
..replies.add({'type': 'schedule_deleted', 'schedule_id': 8});
final repository = SchedulesRepository(gateway);
await repository.deleteSchedule(8, 3);
expect(gateway.calls.single.type, 'delete_schedule');
expect(gateway.calls.single.fields, {
'schedule_id': 8,
'expected_revision': 3,
});
});
test('delete refuses a confirmation for anything else', () async {
final gateway = RecordingGateway();
final repository = SchedulesRepository(gateway);
for (final reply in [
<String, dynamic>{},
{'type': 'pong'},
{'type': 'schedule_deleted'},
{'type': 'schedule_deleted', 'schedule_id': 9},
]) {
gateway.replies.add(reply);
await expectLater(
repository.deleteSchedule(8, 3),
throwsA(
isA<SchedulesRepositoryException>().having(
(error) => error.message,
'message',
'The server did not confirm deletion of this schedule.',
),
),
);
}
});
test('server refusals and conflicts propagate verbatim', () async {
final conflict = const ProtocolError(
'schedule revision conflict; reload before editing',
);
final recording = RecordingGateway()..failure = conflict;
final conflicting = SchedulesRepository(recording);
await expectLater(
conflicting.saveSchedule(createRecord()),
throwsA(same(conflict)),
);
await expectLater(
conflicting.deleteSchedule(8, 3),
throwsA(same(conflict)),
);
final unsupported = const ProtocolError(
'unknown message type: list_schedules',
);
recording.failure = unsupported;
await expectLater(
conflicting.listSchedules(pipelineId: 4),
throwsA(same(unsupported)),
);
});
test('missing and empty list replies are different facts', () async {
final gateway = RecordingGateway();
final repository = SchedulesRepository(gateway);
gateway.replies.add({'type': 'schedules'});
expect(await repository.listSchedules(), isEmpty);
gateway.replies.add({'type': 'schedules', 'schedules': null});
expect(await repository.listSchedules(), isEmpty);
for (final reply in [
<String, dynamic>{},
{'type': 'pong'},
{'type': 'schedules', 'schedules': <String, dynamic>{}},
{
'type': 'schedules',
'schedules': ['not a record'],
},
]) {
gateway.replies.add(reply);
await expectLater(
repository.listSchedules(),
throwsA(isA<SchedulesRepositoryException>()),
);
}
});
test('save requires a saved schedule in the reply', () async {
final gateway = RecordingGateway();
final repository = SchedulesRepository(gateway);
for (final reply in [
<String, dynamic>{},
{'type': 'schedule'},
{'type': 'schedule', 'schedule': null},
{'type': 'schedule', 'schedule': 'record'},
]) {
gateway.replies.add(reply);
await expectLater(
repository.saveSchedule(createRecord()),
throwsA(
isA<SchedulesRepositoryException>().having(
(error) => error.message,
'message',
'The server returned no saved schedule.',
),
),
);
}
});
test('an empty schedule object is not turned into a fake identity', () async {
final gateway = RecordingGateway()
..replies.add({'type': 'schedule', 'schedule': <String, dynamic>{}});
final repository = SchedulesRepository(gateway);
final saved = await repository.saveSchedule(createRecord());
expect(saved.id, isNull);
expect(saved.revision, isNull);
expect(saved.toJson(), isEmpty);
});
}
@@ -0,0 +1,81 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/schedules/data/schedules_repository.dart';
import 'schedule_test_support.dart';
void main() {
test(
'list rejects non-positive and unsafe pipeline IDs before sending',
() async {
final gateway = RecordingGateway();
final repository = SchedulesRepository(gateway);
for (final id in [0, -1, 9007199254740992]) {
await expectLater(
repository.listSchedules(pipelineId: id),
throwsA(
isA<SchedulesRepositoryException>().having(
(error) => error.message,
'message',
'A positive pipeline ID is required.',
),
),
);
}
expect(gateway.calls, isEmpty);
},
);
test(
'delete rejects an inexact identity or revision before sending',
() async {
final gateway = RecordingGateway();
final repository = SchedulesRepository(gateway);
for (final pair in [
(0, 1),
(-1, 1),
(8, 0),
(8, -1),
(8, 9007199254740992),
]) {
await expectLater(
repository.deleteSchedule(pair.$1, pair.$2),
throwsA(
isA<SchedulesRepositoryException>().having(
(error) => error.message,
'message',
'An exact schedule ID and revision are required.',
),
),
);
}
expect(gateway.calls, isEmpty);
},
);
test(
'request keys are bounded at 128 characters like the web client',
() async {
final gateway = RecordingGateway();
final repository = SchedulesRepository(gateway);
await expectLater(
repository.saveSchedule(createRecord(), requestKey: 'x' * 129),
throwsA(
isA<SchedulesRepositoryException>().having(
(error) => error.message,
'message',
'Schedule request keys must be strings of at most 128 characters.',
),
),
);
expect(gateway.calls, isEmpty);
final key = 'x' * 128;
gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()});
await repository.saveSchedule(createRecord(), requestKey: key);
expect(gateway.calls.single.fields['request_key'], key);
},
);
}
@@ -0,0 +1,132 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/schedules/data/schedules_repository.dart';
import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart';
import 'schedule_test_support.dart';
void main() {
test(
'lists with the exact web envelope and retains every record field',
() async {
final record = savedRecord();
final gateway = RecordingGateway()
..replies.add({
'type': 'schedules',
'schedules': [record],
});
final repository = SchedulesRepository(gateway);
final listed = await repository.listSchedules(pipelineId: 4);
expect(gateway.calls.single.type, 'list_schedules');
expect(gateway.calls.single.fields, {'pipeline_id': 4});
expect(listed.single.toJson(), record);
expect(listed.single.pipelineId, 4);
expect(listed.single.version, 2);
expect(listed.single.prompt, 'Research batteries');
expect(listed.single.workspace, '/srv/research');
expect(listed.single.enabled, isTrue);
expect(listed.single.rule.every, '24h');
expect(listed.single.rule.days, ['mon', 'wed']);
expect(listed.single.rule.timezone, 'Europe/London');
expect(listed.single.model, 'openai/gpt-5');
expect(listed.single.notifyMode, 'off');
expect(listed.single.toJson()['future_server_field'], {
'nested': [
1,
2,
{'deep': true},
],
});
gateway.replies.add({'type': 'schedules'});
await repository.listSchedules();
expect(gateway.calls.last.type, 'list_schedules');
expect(gateway.calls.last.fields, isEmpty);
},
);
test(
'create sends the web sentinel record without inventing a revision',
() async {
final create = createRecord();
final original = deepCopy(create);
final gateway = RecordingGateway()
..replies.add({'type': 'schedule', 'schedule': savedRecord()});
final repository = SchedulesRepository(gateway);
final saved = await repository.saveSchedule(create);
expect(gateway.calls.single.type, 'save_schedule');
expect(gateway.calls.single.fields, {'schedule': create});
expect(gateway.calls.single.fields.containsKey('request_key'), isFalse);
expect(
gateway.calls.single.fields.containsKey('expected_revision'),
isFalse,
);
expect(create, original, reason: 'the caller record must be unchanged');
expect(saved.id, 8);
expect(saved.revision, 3);
expect(saved.toJson(), savedRecord());
},
);
test(
'a stable create key is forwarded exactly and blanks are omitted',
() async {
final create = createRecord();
final gateway = RecordingGateway();
final repository = SchedulesRepository(gateway);
gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()});
await repository.saveSchedule(
create,
requestKey: 'schedule:stable-editor-key',
);
expect(gateway.calls.last.fields, {
'schedule': create,
'request_key': 'schedule:stable-editor-key',
});
gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()});
await repository.saveSchedule(create, requestKey: '');
expect(gateway.calls.last.fields, {'schedule': create});
},
);
test('update reuses the read revision as the CAS token', () async {
final current = SavedSchedule(savedRecord());
final paused = current.withEnabled(false);
expect(paused.id, 8);
expect(paused.revision, 3);
expect(paused.toJson()['future_server_field'], isNotNull);
final gateway = RecordingGateway()
..replies.add({
'type': 'schedule',
'schedule': {...savedRecord(), 'enabled': false, 'revision': 4},
});
final repository = SchedulesRepository(gateway);
final updated = await repository.saveSchedule(paused.toJson());
final body = gateway.calls.single.fields['schedule'] as Map;
expect(gateway.calls.single.type, 'save_schedule');
expect(gateway.calls.single.fields.containsKey('request_key'), isFalse);
expect(
gateway.calls.single.fields.containsKey('expected_revision'),
isFalse,
);
expect(body['id'], 8);
expect(body['revision'], 3);
expect(body['enabled'], isFalse);
expect(body['future_server_field'], isNotNull);
expect(updated.revision, 4);
expect(updated.enabled, isFalse);
// The stale draft keeps its token: a conflict must not be papered over by
// silently adopting the reply revision.
expect(current.revision, 3);
expect(current.enabled, isTrue);
});
}
@@ -0,0 +1,182 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/schedules/data/schedules_repository.dart';
import 'package:pipelines_app/features/schedules/ui/list/schedule_list_controller.dart';
import 'schedule_list_test_support.dart';
SchedulesController controllerFor(ApiGateway gateway, {int? pipelineId}) =>
SchedulesController(
repository: SchedulesRepository(gateway),
pipelineId: pipelineId,
);
void main() {
test('lists schedules with the optional pipeline envelope', () async {
final gateway = FakeSchedulesGateway(
(type, fields) async =>
schedulesReply([scheduleRecord(), pausedRecord()]),
);
final controller = controllerFor(gateway, pipelineId: 4);
addTearDown(controller.dispose);
await controller.refresh();
expect(gateway.calls.single.type, 'list_schedules');
expect(gateway.calls.single.fields, {'pipeline_id': 4});
expect(controller.schedules.map((schedule) => schedule.name), [
'Research batteries',
'Nightly report',
]);
expect(controller.hasLoaded, isTrue);
expect(controller.failure, isNull);
expect(controller.countLabel, '2 schedules');
final globalGateway = FakeSchedulesGateway(
(type, fields) async => schedulesReply([scheduleRecord()]),
);
final global = controllerFor(globalGateway);
addTearDown(global.dispose);
await global.refresh();
expect(globalGateway.calls.single.fields, isEmpty);
});
test('an empty reply is loaded empty, not an unsupported server', () async {
final gateway = FakeSchedulesGateway(
(type, fields) async => {'type': 'schedules'},
);
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
await controller.refresh();
expect(controller.hasLoaded, isTrue);
expect(controller.schedules, isEmpty);
expect(controller.failure, isNull);
expect(controller.countLabel, '0 schedules');
});
test('an unsupported envelope is distinct from empty and errors', () async {
final unsupported = controllerFor(
FakeSchedulesGateway((type, fields) async => {'type': 'runs'}),
);
addTearDown(unsupported.dispose);
await unsupported.refresh();
expect(unsupported.failure?.unsupported, isTrue);
expect(unsupported.failure?.message, contains('does not support'));
expect(unsupported.failure?.message, contains('Upgrade the server'));
expect(unsupported.hasLoaded, isFalse);
final failed = controllerFor(
FakeSchedulesGateway(
(type, fields) async => throw StateError('socket closed'),
),
);
addTearDown(failed.dispose);
await failed.refresh();
expect(failed.failure?.unsupported, isFalse);
expect(failed.failure?.message, contains('socket closed'));
expect(failed.hasLoaded, isFalse);
});
test(
'an older server refusal gets the same upgrade guidance as web',
() async {
for (final text in [
'unknown request: list_schedules',
'UNKNOWN COMMAND list_schedules',
'Unsupported schedules command',
]) {
final controller = controllerFor(
FakeSchedulesGateway(
(type, fields) async => throw SchedulesRepositoryException(text),
),
);
addTearDown(controller.dispose);
await controller.refresh();
expect(controller.failure?.unsupported, isTrue, reason: text);
expect(controller.failure?.message, contains('Upgrade the server'));
expect(controller.failure?.message, contains(text));
}
final unrelated = controllerFor(
FakeSchedulesGateway(
(type, fields) async =>
throw const SchedulesRepositoryException('Permission denied.'),
),
);
addTearDown(unrelated.dispose);
await unrelated.refresh();
expect(unrelated.failure?.unsupported, isFalse);
expect(unrelated.failure?.message, 'Permission denied.');
},
);
test('a failed refresh keeps the previously loaded schedules', () async {
var fail = false;
final gateway = FakeSchedulesGateway((type, fields) async {
if (fail) throw StateError('refresh failed');
return schedulesReply([scheduleRecord()]);
});
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
await controller.refresh();
fail = true;
await controller.refresh();
expect(controller.schedules.single.name, 'Research batteries');
expect(controller.failure?.message, contains('refresh failed'));
expect(controller.isLoading, isFalse);
});
test('only the newest refresh may publish a reply', () async {
final gateway = ControlledSchedulesGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
final first = controller.refresh();
final second = controller.refresh();
expect(gateway.requests, hasLength(2));
gateway.complete(1, schedulesReply([scheduleRecord(name: 'Newest reply')]));
await second;
gateway.complete(0, schedulesReply([scheduleRecord(name: 'Stale reply')]));
await first;
expect(controller.schedules.single.name, 'Newest reply');
expect(controller.isLoading, isFalse);
});
test('a reply arriving after dispose is ignored safely', () async {
final gateway = ControlledSchedulesGateway();
final controller = controllerFor(gateway);
var notifications = 0;
controller.addListener(() => notifications++);
final pending = controller.refresh();
expect(notifications, 1);
controller.dispose();
gateway.complete(0, schedulesReply([scheduleRecord()]));
await expectLater(pending, completes);
expect(notifications, 1);
});
test('missing server fields stay visible as unavailable values', () async {
final gateway = FakeSchedulesGateway(
(type, fields) async => schedulesReply([sparseRecord()]),
);
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
await controller.refresh();
final schedule = controller.schedules.single;
expect(schedule.name, isEmpty);
expect(schedule.pipelineId, isNull);
expect(schedule.version, isNull);
expect(schedule.workspace, isEmpty);
expect(schedule.nextDue, isEmpty);
});
}
@@ -0,0 +1,87 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/schedules/data/schedules_repository.dart';
import 'package:pipelines_app/features/schedules/ui/list/schedule_list_controller.dart';
import 'schedule_list_test_support.dart';
SchedulesController controllerFor(ApiGateway gateway) =>
SchedulesController(repository: SchedulesRepository(gateway));
void main() {
test(
'search covers name, prompt and pipeline; enabled filters rows',
() async {
final gateway = FakeSchedulesGateway(
(type, fields) async =>
schedulesReply([scheduleRecord(), pausedRecord()]),
);
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
await controller.refresh();
controller.setQuery('research');
expect(controller.visibleSchedules.single.name, 'Research batteries');
controller.setQuery('BATTERY CHEMISTRY');
expect(controller.visibleSchedules.single.id, 8);
controller.setQuery('pipeline 7');
expect(controller.visibleSchedules.single.name, 'Nightly report');
expect(controller.countLabel, '1 of 2 schedules');
controller.setQuery('pipeline unavailable');
expect(controller.visibleSchedules, isEmpty);
controller.clearQuery();
controller.setFilter(ScheduleListFilter.enabled);
expect(controller.visibleSchedules.single.name, 'Research batteries');
expect(controller.emptyMessage, 'No enabled schedules.');
await controller.refresh();
expect(controller.filter, ScheduleListFilter.enabled);
expect(controller.visibleSchedules.single.name, 'Research batteries');
controller.setQuery('unmatched');
expect(controller.visibleSchedules, isEmpty);
expect(controller.countLabel, '0 of 2 schedules');
expect(controller.emptyMessage, 'No schedules match this search.');
},
);
test(
'the filtered view is recomputed for query, filter and new replies',
() async {
var records = [scheduleRecord(), pausedRecord()];
final gateway = FakeSchedulesGateway(
(type, fields) async => schedulesReply(records),
);
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
await controller.refresh();
expect(controller.visibleSchedules, hasLength(2));
controller.setQuery('nightly');
expect(controller.visibleSchedules.single.name, 'Nightly report');
controller.clearQuery();
controller.setFilter(ScheduleListFilter.enabled);
expect(controller.visibleSchedules.single.name, 'Research batteries');
records = [
scheduleRecord(id: 20, name: 'Renamed', enabled: false),
scheduleRecord(id: 21, name: 'Fresh'),
];
await controller.refresh();
expect(controller.visibleSchedules.single.name, 'Fresh');
expect(controller.countLabel, '1 of 2 schedules');
controller.setFilter(ScheduleListFilter.all);
expect(controller.visibleSchedules.map((schedule) => schedule.name), [
'Renamed',
'Fresh',
]);
},
);
}
@@ -0,0 +1,72 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart';
import 'package:pipelines_app/features/schedules/ui/list/schedule_list_format.dart';
import 'schedule_list_test_support.dart';
void main() {
test('formats complete server values', () {
final schedule = SavedSchedule(scheduleRecord());
expect(scheduleDisplayName(schedule), 'Research batteries');
expect(scheduleStatusLabel(schedule), 'Enabled');
expect(schedulePipelineVersionValue(schedule), 'Pipeline 4 · v2');
expect(scheduleWorkspaceValue(schedule), '/srv/research');
expect(scheduleTimerValue(schedule), 'Every 24h · mon, wed');
expect(scheduleTimezoneValue(schedule), 'Europe/London');
expect(scheduleNextDueValue(schedule), scheduleDueValue(schedule.nextDue));
});
test('formats clock rules and the server timezone fallback', () {
final schedule = SavedSchedule(pausedRecord());
expect(scheduleStatusLabel(schedule), 'Paused');
expect(scheduleTimerValue(schedule), '10:00, 18:30');
expect(scheduleTimezoneValue(schedule), 'Server timezone');
expect(scheduleNextDueValue(schedule), 'Paused');
});
test('missing server values are honest, never invented', () {
final schedule = SavedSchedule(sparseRecord());
expect(scheduleDisplayName(schedule), 'Unnamed schedule');
expect(
schedulePipelineVersionValue(schedule),
'Pipeline unavailable · Version unavailable',
);
expect(scheduleWorkspaceValue(schedule), 'Workspace unavailable');
expect(scheduleTimerValue(schedule), 'Timer unavailable');
expect(scheduleTimezoneValue(schedule), 'Server timezone');
expect(scheduleNextDueValue(schedule), 'Paused');
final enabled = SavedSchedule(scheduleRecord(nextDue: null));
expect(scheduleNextDueValue(enabled), 'Not scheduled');
final invalid = SavedSchedule(scheduleRecord(nextDue: 'tomorrow'));
expect(scheduleNextDueValue(invalid), 'Next time unavailable');
});
test('due values are shown in local time and keep invalid input honest', () {
expect(
scheduleDueValue('2026-10-22T09:00:00'),
'2026-10-22 09:00 (your local time)',
);
final value = scheduleDueValue('2026-10-22T09:00:00Z');
final local = DateTime.parse('2026-10-22T09:00:00Z').toLocal();
String two(int part) => part.toString().padLeft(2, '0');
expect(
value,
'${local.year}-${two(local.month)}-${two(local.day)} '
'${two(local.hour)}:${two(local.minute)} (your local time)',
);
expect(scheduleDueValue('not a date'), 'Next time unavailable');
});
test('count wording covers single, plural, filtered and empty lists', () {
expect(scheduleCountLabel(1, 1), '1 schedule');
expect(scheduleCountLabel(2, 2), '2 schedules');
expect(scheduleCountLabel(1, 2), '1 of 2 schedules');
expect(scheduleCountLabel(0, 0), '0 schedules');
});
}
@@ -0,0 +1,143 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/core/api_gateway.dart';
typedef ScheduleHandler = Future<JsonMap> Function(String type, JsonMap fields);
class RecordedScheduleCall {
const RecordedScheduleCall(this.type, this.fields);
final String type;
final JsonMap fields;
}
/// Records every request and replays the handler's reply. No socket is opened.
class FakeSchedulesGateway implements ApiGateway {
FakeSchedulesGateway(this.handler);
final ScheduleHandler handler;
final calls = <RecordedScheduleCall>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
calls.add(RecordedScheduleCall(type, Map<String, dynamic>.from(fields)));
return handler(type, Map<String, dynamic>.from(fields));
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
/// Holds each request open so a test can complete replies out of order or after
/// the screen is gone.
class ControlledSchedulesGateway implements ApiGateway {
final calls = <RecordedScheduleCall>[];
final requests = <Completer<JsonMap>>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
calls.add(RecordedScheduleCall(type, Map<String, dynamic>.from(fields)));
final request = Completer<JsonMap>();
requests.add(request);
return request.future;
}
void complete(int index, JsonMap reply) => requests[index].complete(reply);
void fail(int index, Object error) => requests[index].completeError(error);
@override
Stream<JsonMap> get frames => const Stream.empty();
}
JsonMap schedulesReply(List<JsonMap> items) => {
'type': 'schedules',
'schedules': items,
};
JsonMap scheduleRecord({
int? id = 8,
int? revision = 3,
String name = 'Research batteries',
int? pipelineId = 4,
int? version = 2,
bool enabled = true,
String prompt = 'Find battery chemistry sources',
String workspace = '/srv/research',
Map<String, dynamic> rule = const {
'every': '24h',
'days': ['mon', 'wed'],
'timezone': 'Europe/London',
},
String? nextDue = '2026-10-22T09:00:00Z',
}) => {
'id': ?id,
'revision': ?revision,
'name': name,
'pipeline_id': ?pipelineId,
'version': ?version,
'enabled': enabled,
'input': {'prompt': prompt},
'workspace': workspace,
'rule': rule,
'next_due': ?nextDue,
};
JsonMap pausedRecord() => scheduleRecord(
id: 9,
revision: 1,
name: 'Nightly report',
pipelineId: 7,
version: 5,
enabled: false,
prompt: 'Summarise the open issues',
workspace: '/srv/reports',
rule: const {
'times': ['10:00', '18:30'],
'days': <String>[],
'timezone': 'Local',
},
nextDue: null,
);
JsonMap sparseRecord() => {
'id': 11,
'name': '',
'enabled': false,
'input': <String, dynamic>{},
'rule': <String, dynamic>{},
};
List<JsonMap> longScheduleList(int count) => [
for (var index = 0; index < count; index++)
scheduleRecord(
id: 100 + index,
revision: 1,
name: 'Topic $index',
prompt: 'Prompt $index',
),
];
Widget schedulesApp(
Widget child, {
required bool cupertino,
double textScale = 1,
}) {
Widget media(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: app!,
);
if (cupertino) {
return CupertinoApp(
builder: media,
home: CupertinoPageScaffold(child: SafeArea(child: child)),
);
}
return MaterialApp(
builder: media,
home: Scaffold(body: child),
);
}
@@ -0,0 +1,33 @@
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/schedules/domain/saved_schedule.dart';
import 'package:pipelines_app/features/schedules/screen.dart';
import 'schedule_list_test_support.dart';
Future<void> pumpSchedules(
WidgetTester tester, {
required bool cupertino,
required ApiGateway gateway,
ValueChanged<SavedSchedule>? onOpen,
double textScale = 1,
bool settle = true,
}) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
schedulesApp(
SchedulesScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
cupertino: cupertino,
textScale: textScale,
),
);
if (settle) {
await tester.pumpAndSettle();
} else {
await tester.pump();
}
}
@@ -0,0 +1,79 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/schedules/ui/list/schedule_list_controller.dart';
import 'package:pipelines_app/features/schedules/ui/list/schedule_list_toolbar.dart';
import 'package:pipelines_app/features/schedules/ui/list/schedule_list_view.dart';
import 'schedule_list_test_support.dart';
import 'schedule_screen_harness.dart';
void main() {
for (final cupertino in [false, true]) {
for (final textScale in [1.0, 2.0]) {
testWidgets('${cupertino ? 'Cupertino' : 'Material'} list at 390px and '
'${textScale}x text shows server values with native controls', (
tester,
) async {
final gateway = FakeSchedulesGateway(
(type, fields) async => schedulesReply([
scheduleRecord(nextDue: '2026-10-22T09:00:00'),
pausedRecord(),
]),
);
await pumpSchedules(
tester,
cupertino: cupertino,
gateway: gateway,
textScale: textScale,
);
expect(find.text('2 schedules'), findsOneWidget);
expect(find.textContaining('not pipeline definitions'), findsOneWidget);
expect(find.text('Research batteries'), findsOneWidget);
expect(find.text('Find battery chemistry sources'), findsOneWidget);
expect(find.text('Pipeline 4 · v2'), findsOneWidget);
expect(find.text('Workspace: /srv/research'), findsOneWidget);
expect(find.text('Timer: Every 24h · mon, wed'), findsOneWidget);
expect(find.text('Timezone: Europe/London'), findsOneWidget);
expect(
find.text('Next due: 2026-10-22 09:00 (your local time)'),
findsOneWidget,
);
await tester.scrollUntilVisible(
find.text('Nightly report'),
300,
scrollable: find.descendant(
of: find.byKey(scheduleListKey),
matching: find.byType(Scrollable),
),
);
expect(find.text('Nightly report'), findsOneWidget);
expect(find.text('Pipeline 7 · v5'), findsOneWidget);
expect(find.text('Workspace: /srv/reports'), findsOneWidget);
expect(find.text('Timer: 10:00, 18:30'), findsOneWidget);
expect(find.text('Timezone: Server timezone'), findsOneWidget);
expect(find.text('Next due: Paused'), findsOneWidget);
if (cupertino) {
expect(find.byType(CupertinoSearchTextField), findsOneWidget);
expect(
find.byType(CupertinoSlidingSegmentedControl<ScheduleListFilter>),
findsOneWidget,
);
expect(find.byType(CupertinoButton), findsWidgets);
expect(find.byType(TextField), findsNothing);
} else {
expect(find.byKey(scheduleSearchFieldKey), findsOneWidget);
expect(
find.byType(SegmentedButton<ScheduleListFilter>),
findsOneWidget,
);
expect(find.byType(TextField), findsOneWidget);
}
expect(tester.takeException(), isNull);
});
}
}
}
@@ -0,0 +1,119 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/schedules/ui/list/schedule_list_toolbar.dart';
import 'package:pipelines_app/features/schedules/ui/list/schedule_list_view.dart';
import 'schedule_list_test_support.dart';
import 'schedule_screen_harness.dart';
void main() {
testWidgets('refresh keeps the search query and its filtered rows', (
tester,
) async {
final gateway = FakeSchedulesGateway(
(type, fields) async =>
schedulesReply([scheduleRecord(), pausedRecord()]),
);
await pumpSchedules(tester, cupertino: false, gateway: gateway);
await tester.enterText(
find.byKey(scheduleSearchFieldKey),
'battery chemistry',
);
await tester.pump();
expect(find.text('Research batteries'), findsOneWidget);
expect(find.text('Nightly report'), findsNothing);
await tester.tap(find.byKey(scheduleRefreshKey));
await tester.pumpAndSettle();
final field = tester.widget<TextField>(find.byKey(scheduleSearchFieldKey));
expect(field.controller?.text, 'battery chemistry');
expect(find.text('Research batteries'), findsOneWidget);
expect(find.text('Nightly report'), findsNothing);
expect(gateway.calls, hasLength(2));
expect(
gateway.calls.every((call) => call.type == 'list_schedules'),
isTrue,
);
});
testWidgets('refresh preserves the list scroll offset', (tester) async {
final gateway = FakeSchedulesGateway(
(type, fields) async => schedulesReply(longScheduleList(30)),
);
await pumpSchedules(tester, cupertino: false, gateway: gateway);
final list = find.byKey(scheduleListKey);
await tester.drag(list, const Offset(0, -700));
await tester.pumpAndSettle();
final before = tester.widget<ListView>(list).controller!.offset;
expect(before, greaterThan(0));
await tester.tap(find.byKey(scheduleRefreshKey));
await tester.pumpAndSettle();
final after = tester.widget<ListView>(list).controller!.offset;
expect(after, before);
expect(tester.takeException(), isNull);
});
testWidgets('a failed refresh keeps the scroll offset and the rows', (
tester,
) async {
var fail = false;
final gateway = FakeSchedulesGateway((type, fields) async {
if (fail) throw StateError('refresh failed');
return schedulesReply(longScheduleList(30));
});
await pumpSchedules(tester, cupertino: false, gateway: gateway);
final list = find.byKey(scheduleListKey);
await tester.drag(list, const Offset(0, -700));
await tester.pumpAndSettle();
final before = tester.widget<ListView>(list).controller!.offset;
expect(before, greaterThan(0));
fail = true;
await tester.tap(find.byKey(scheduleRefreshKey));
await tester.pumpAndSettle();
expect(find.textContaining('refresh failed'), findsOneWidget);
expect(
tester.widget<ListView>(find.byKey(scheduleListKey)).controller!.offset,
before,
);
fail = false;
await tester.tap(find.byKey(scheduleRetryKey));
await tester.pumpAndSettle();
expect(find.textContaining('refresh failed'), findsNothing);
expect(
tester.widget<ListView>(find.byKey(scheduleListKey)).controller!.offset,
before,
);
expect(tester.takeException(), isNull);
});
testWidgets('a failed refresh keeps rows and reports the error', (
tester,
) async {
var fail = false;
final gateway = FakeSchedulesGateway((type, fields) async {
if (fail) throw StateError('refresh failed');
return schedulesReply([scheduleRecord(), pausedRecord()]);
});
await pumpSchedules(tester, cupertino: false, gateway: gateway);
fail = true;
await tester.tap(find.byKey(scheduleRefreshKey));
await tester.pumpAndSettle();
expect(find.text('Research batteries'), findsOneWidget);
expect(find.text('Nightly report'), findsOneWidget);
expect(find.textContaining('refresh failed'), findsOneWidget);
expect(find.byKey(scheduleRetryKey), findsOneWidget);
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,171 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart';
import 'package:pipelines_app/features/schedules/ui/list/schedule_list_row.dart';
import 'package:pipelines_app/features/schedules/ui/list/schedule_list_toolbar.dart';
import 'package:pipelines_app/features/schedules/ui/list/schedule_list_view.dart';
import 'schedule_list_test_support.dart';
import 'schedule_screen_harness.dart';
void main() {
testWidgets('search covers name, prompt and pipeline in both themes', (
tester,
) async {
for (final cupertino in [false, true]) {
final gateway = FakeSchedulesGateway(
(type, fields) async =>
schedulesReply([scheduleRecord(), pausedRecord()]),
);
await pumpSchedules(tester, cupertino: cupertino, gateway: gateway);
await tester.enterText(find.byKey(scheduleSearchFieldKey), 'pipeline 7');
await tester.pump();
expect(find.text('Nightly report'), findsOneWidget);
expect(find.text('Research batteries'), findsNothing);
expect(find.text('1 of 2 schedules'), findsOneWidget);
await tester.enterText(
find.byKey(scheduleSearchFieldKey),
'battery chemistry',
);
await tester.pump();
expect(find.text('Research batteries'), findsOneWidget);
expect(find.text('Nightly report'), findsNothing);
await tester.enterText(find.byKey(scheduleSearchFieldKey), 'no match');
await tester.pump();
expect(find.text('No schedules match this search.'), findsOneWidget);
expect(tester.takeException(), isNull);
}
});
testWidgets('enabled filter removes paused schedules in both themes', (
tester,
) async {
for (final cupertino in [false, true]) {
final gateway = FakeSchedulesGateway(
(type, fields) async =>
schedulesReply([scheduleRecord(), pausedRecord()]),
);
await pumpSchedules(tester, cupertino: cupertino, gateway: gateway);
await tester.tap(
find.descendant(
of: find.byKey(scheduleFilterKey),
matching: find.text('Enabled'),
),
);
await tester.pumpAndSettle();
expect(find.text('Research batteries'), findsOneWidget);
expect(find.text('Nightly report'), findsNothing);
expect(find.text('1 of 2 schedules'), findsOneWidget);
expect(tester.takeException(), isNull);
}
});
testWidgets('row selection opens the exact record and never mutates', (
tester,
) async {
final record = scheduleRecord();
final gateway = FakeSchedulesGateway(
(type, fields) async => schedulesReply([record]),
);
final opened = <SavedSchedule>[];
await pumpSchedules(
tester,
cupertino: false,
gateway: gateway,
onOpen: opened.add,
);
expect(opened, isEmpty);
expect(find.text('Add schedule'), findsNothing);
expect(find.text('Edit'), findsNothing);
expect(find.text('Delete'), findsNothing);
expect(find.text('Pause'), findsNothing);
await tester.tap(find.byType(ScheduleListRow));
await tester.pumpAndSettle();
expect(opened, hasLength(1));
expect(opened.single.raw, equals(record));
expect(gateway.calls.map((call) => call.type), ['list_schedules']);
});
testWidgets('empty and unsupported or failed replies stay distinct', (
tester,
) async {
final empty = FakeSchedulesGateway(
(type, fields) async => {'type': 'schedules'},
);
await pumpSchedules(tester, cupertino: false, gateway: empty);
expect(find.text('No schedules yet.'), findsOneWidget);
expect(find.byKey(scheduleRetryKey), findsNothing);
final unsupported = FakeSchedulesGateway(
(type, fields) async => {'type': 'runs'},
);
await pumpSchedules(tester, cupertino: false, gateway: unsupported);
expect(
find.textContaining('does not support saved schedules'),
findsOneWidget,
);
expect(find.byKey(scheduleRetryKey), findsOneWidget);
expect(find.text('No schedules yet.'), findsNothing);
final failed = FakeSchedulesGateway(
(type, fields) async => throw StateError('socket closed'),
);
await pumpSchedules(tester, cupertino: false, gateway: failed);
expect(find.textContaining('socket closed'), findsOneWidget);
expect(find.byKey(scheduleRetryKey), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('an empty search with the enabled filter names the filter', (
tester,
) async {
final gateway = FakeSchedulesGateway(
(type, fields) async => schedulesReply([pausedRecord()]),
);
await pumpSchedules(tester, cupertino: false, gateway: gateway);
await tester.tap(
find.descendant(
of: find.byKey(scheduleFilterKey),
matching: find.text('Enabled'),
),
);
await tester.pumpAndSettle();
expect(find.text('0 of 1 schedules'), findsOneWidget);
expect(find.text('No enabled schedules.'), findsOneWidget);
expect(find.text('No schedules match this search.'), findsNothing);
await tester.enterText(find.byKey(scheduleSearchFieldKey), 'nightly');
await tester.pump();
expect(find.text('No schedules match this search.'), findsOneWidget);
expect(find.text('No enabled schedules.'), findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('late reply after the screen is disposed does not throw', (
tester,
) async {
final gateway = ControlledSchedulesGateway();
await pumpSchedules(
tester,
cupertino: false,
gateway: gateway,
settle: false,
);
expect(find.byKey(scheduleRefreshKey), findsNothing);
await tester.pumpWidget(const SizedBox.shrink());
gateway.complete(0, schedulesReply([scheduleRecord()]));
await tester.pump();
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,90 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/search/domain/search_controller.dart';
import 'package:pipelines_app/features/search/domain/search_query.dart';
import 'search_test_support.dart';
void main() {
test('a server error is shown, and retry issues a fresh request', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('plan');
await pumpEventQueue();
gateway.fail(0, StateError('server is down'));
await pumpEventQueue();
expect(controller.bodyKind, SearchBodyKind.error);
expect(controller.error, contains('server is down'));
final retry = controller.retry();
await pumpEventQueue();
expect(gateway.calls, hasLength(2));
expect(gateway.lastSearch, {'query': 'plan', 'kind': '', 'limit': 0});
gateway.succeed(
1,
envelope([
{
'kind': 'pipeline',
'target': 'pipeline:7',
'pipeline': {'id': 7},
},
]),
);
await retry;
expect(controller.error, isNull);
expect(controller.results, hasLength(1));
expect(controller.bodyKind, SearchBodyKind.results);
});
test('a stale failure never replaces the newest query state', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('first');
await pumpEventQueue();
controller.updateQuery('second');
await pumpEventQueue();
gateway.fail(0, StateError('stale failure'));
await pumpEventQueue();
expect(controller.error, isNull);
expect(controller.loading, isTrue);
expect(controller.bodyKind, SearchBodyKind.searching);
gateway.succeed(
1,
envelope([
{
'kind': 'pipeline',
'target': 'pipeline:9',
'pipeline': {'id': 9},
},
]),
);
await pumpEventQueue();
expect(controller.error, isNull);
expect(controller.results.single['target'], 'pipeline:9');
expect(controller.bodyKind, SearchBodyKind.results);
});
test(
'a missing search_results payload reports the unsupported copy',
() async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('plan');
await pumpEventQueue();
gateway.succeed(0, {'type': 'pong'});
await pumpEventQueue();
expect(controller.bodyKind, SearchBodyKind.error);
expect(controller.error, unsupportedSearchCopy);
},
);
}
@@ -0,0 +1,240 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/search/domain/search_controller.dart';
import 'package:pipelines_app/features/search/domain/search_models.dart';
import 'search_test_support.dart';
void main() {
test('empty query with no kind is idle and sends no request', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery(' ');
await pumpEventQueue();
expect(gateway.calls, isEmpty);
expect(controller.bodyKind, SearchBodyKind.idle);
expect(controller.results, isEmpty);
expect(controller.loaded, isFalse);
expect(controller.loading, isFalse);
});
test('the request carries the parsed query, kind and limit 0', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('t:run Plan TYPE:artifact');
await pumpEventQueue();
expect(gateway.calls, hasLength(1));
expect(gateway.lastSearch, {
'query': 'Plan',
'kind': 'artifact',
'limit': 0,
});
});
test(
'a kind selector change removes type tokens and sends at once',
() async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('plan t:run');
await pumpEventQueue();
expect(gateway.lastSearch['kind'], 'run');
controller.selectKind(SearchKind.pipeline);
await pumpEventQueue();
expect(controller.query.trim(), 'plan');
expect(controller.query, isNot(contains('t:run')));
expect(controller.selectedKind, SearchKind.pipeline);
expect(gateway.calls, hasLength(2));
expect(gateway.lastSearch, {
'query': 'plan',
'kind': 'pipeline',
'limit': 0,
});
},
);
test(
'kind-only browsing sends a blank query and reports the empty copy',
() async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.selectKind(SearchKind.pipeline);
await pumpEventQueue();
expect(gateway.lastSearch, {'query': '', 'kind': 'pipeline', 'limit': 0});
expect(controller.bodyKind, SearchBodyKind.searching);
gateway.succeed(0, envelope(const []));
await pumpEventQueue();
expect(controller.bodyKind, SearchBodyKind.empty);
expect(controller.emptyMessage, 'No pipelines yet.');
},
);
test('the latest query wins and a stale reply is dropped', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('first');
await pumpEventQueue();
controller.updateQuery('second');
await pumpEventQueue();
expect(gateway.calls, hasLength(2));
gateway.succeed(
0,
envelope([
{
'kind': 'run',
'target': 'run:1',
'run': {'id': 1},
},
]),
);
await pumpEventQueue();
expect(controller.results, isEmpty);
expect(controller.loading, isTrue);
expect(controller.bodyKind, SearchBodyKind.searching);
gateway.succeed(
1,
envelope([
{
'kind': 'run',
'target': 'run:2',
'run': {'id': 2},
},
]),
);
await pumpEventQueue();
expect(controller.results.single['target'], 'run:2');
expect(controller.loading, isFalse);
expect(controller.bodyKind, SearchBodyKind.results);
});
test('truncation and scan bounds come from the server envelope', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('plan');
await pumpEventQueue();
gateway.succeed(
0,
envelope(
[
{
'kind': 'field',
'target': 'run:11:4:output',
'field': {'run_id': 11},
},
],
truncated: true,
scannedSteps: 2000,
scannedBytes: 1048576,
cap: 50,
),
);
await pumpEventQueue();
expect(controller.truncated, isTrue);
expect(controller.scannedSteps, 2000);
expect(controller.scannedBytes, 1048576);
expect(controller.cap, 50);
expect(controller.boundsText, contains('truncated'));
expect(controller.boundsText, contains('cap 50'));
expect(controller.boundsText, contains('2000 steps'));
});
test(
'a truncated empty reply reports the scan bound instead of a complete empty',
() async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('needle');
await pumpEventQueue();
gateway.succeed(
0,
envelope(
const [],
truncated: true,
scannedSteps: 2000,
scannedBytes: 1048576,
cap: 50,
),
);
await pumpEventQueue();
expect(controller.bodyKind, SearchBodyKind.empty);
expect(
controller.emptyMessage,
'No matches for "needle" within the server\'s scan limit.',
);
expect(controller.boundsText, contains('Results truncated'));
expect(controller.boundsText, contains('0 results'));
expect(controller.boundsText, contains('2000 steps'));
expect(controller.boundsText, contains('scan limit 1.0 MiB'));
},
);
test(
'a complete empty reply stays a plain empty with no bounds line',
() async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('needle');
await pumpEventQueue();
gateway.succeed(0, envelope(const []));
await pumpEventQueue();
expect(controller.bodyKind, SearchBodyKind.empty);
expect(controller.emptyMessage, 'No matches for "needle".');
expect(controller.boundsText, isNull);
},
);
test('in-hand kind narrowing keeps the list honest while loading', () async {
final gateway = QueuedGateway();
final controller = controllerFor(gateway);
addTearDown(controller.dispose);
controller.updateQuery('plan');
await pumpEventQueue();
gateway.succeed(
0,
envelope([
{
'kind': 'run',
'target': 'run:1',
'run': {'id': 1},
},
{
'kind': 'pipeline',
'target': 'pipeline:7',
'pipeline': {'id': 7},
},
]),
);
await pumpEventQueue();
expect(controller.shownResults, hasLength(2));
controller.selectKind(SearchKind.run);
await pumpEventQueue();
expect(controller.shownResults, hasLength(1));
expect(controller.shownResults.single['target'], 'run:1');
});
}
@@ -0,0 +1,118 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/search/domain/search_models.dart';
import 'package:pipelines_app/features/search/domain/search_query.dart';
const unsupported =
'This server does not support search. Update the Pipelines server, then try again.';
void main() {
test('kind vocabulary is exactly the server vocabulary, All kinds first', () {
expect(SearchKind.values.map((kind) => kind.wire), [
'',
'pipeline',
'run',
'step',
'field',
'artifact',
'version',
]);
expect(SearchKind.values.map((kind) => kind.label), [
'All kinds',
'Pipelines',
'Runs',
'Steps',
'Fields',
'Artifacts',
'Versions',
]);
expect(SearchKind.fromWire('run'), SearchKind.run);
expect(SearchKind.fromWire(''), SearchKind.all);
expect(SearchKind.fromWire('prompts'), SearchKind.all);
expect(SearchKind.fromWire(null), SearchKind.all);
});
test('both type aliases and kinds are case insensitive', () {
for (final kind in SearchKind.values.where(
(kind) => kind != SearchKind.all,
)) {
for (final prefix in ['t', 'type', 'T', 'TyPe']) {
final parsed = parseSearchQuery(
'$prefix:${kind.wire.toUpperCase()} plan',
);
expect(parsed.query, ' plan');
expect(parsed.kind, kind);
expect(parsed.hasType, isTrue);
}
}
});
test('normal, quoted and unsupported text is preserved byte for byte', () {
const preserved = [
' ordinary text\twith\nspacing ',
'"t:pipeline" "hello world"',
"'type:artifact'",
'"escaped \\" t:run"',
'"unclosed t:run',
't:prompt type:unknown t: t:PIPELINES',
'not:t:run t:run,',
'prefix"t:run"',
'\\t:run',
];
for (final query in preserved) {
final parsed = parseSearchQuery(query, SearchKind.field);
expect(parsed.query, query);
expect(parsed.kind, SearchKind.field);
expect(parsed.hasType, isFalse);
}
expect(
parseSearchQuery('t:artifact "t:pipeline" report').query,
' "t:pipeline" report',
);
});
test('last supported token wins over the selector; unknown tokens stay', () {
final parsed = parseSearchQuery(
't:run plan TYPE:artifact t:unknown',
SearchKind.pipeline,
);
expect(parsed.query, ' plan t:unknown');
expect(parsed.kind, SearchKind.artifact);
expect(parsed.hasType, isTrue);
expect(parseSearchQuery('plan', SearchKind.step).kind, SearchKind.step);
});
test('type-only query is distinguishable from literal and blank input', () {
final typed = parseSearchQuery('t:pipeline');
expect(typed.query, '');
expect(typed.kind, SearchKind.pipeline);
expect(typed.hasType, isTrue);
final blank = parseSearchQuery('');
expect(blank.query, '');
expect(blank.kind, SearchKind.all);
expect(blank.hasType, isFalse);
});
test('blank text is sendable only with a supported nonempty kind', () {
for (final kind in SearchKind.values) {
expect(searchQuerySendable(' \n\t ', kind), kind != SearchKind.all);
}
expect(searchQuerySendable('', SearchKind.all), isFalse);
expect(searchQuerySendable('plan', SearchKind.all), isTrue);
expect(searchQuerySendable(' plan ', SearchKind.all), isTrue);
});
test(
'failure copy distinguishes an unsupported server from a plain error',
() {
expect(searchFailureText(null), unsupported);
expect(searchFailureText(' '), unsupported);
expect(searchFailureText('unknown command: search'), unsupported);
expect(searchFailureText('unsupported command'), unsupported);
expect(searchFailureText('boom'), 'boom');
expect(
searchFailureText('request timed out after 30000ms'),
'request timed out after 30000ms',
);
},
);
}
@@ -0,0 +1,106 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/search/data/search_repository.dart';
import 'package:pipelines_app/features/search/domain/search_models.dart';
class RecordingGateway implements ApiGateway {
String? type;
JsonMap fields = {};
JsonMap reply = {};
Object? failure;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
this.type = type;
this.fields = Map.of(fields);
if (failure case final error?) throw error;
return reply;
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
void main() {
test(
'search sends exactly search/query/kind/limit and parses bounds',
() async {
final gateway = RecordingGateway()
..reply = {
'search_results': {
'query': 'plan',
'kind': 'run',
'results': [
{
'kind': 'run',
'target': 'run:11',
'run': {'id': 11},
},
],
'truncated': true,
'scanned_steps': 27,
'scanned_bytes': 4096,
'cap': 50,
'scan_bound_bytes': 1048576,
},
};
final repository = SearchRepository(gateway);
final response = await repository.search(
query: 'plan',
kind: SearchKind.run,
);
expect(gateway.type, 'search');
expect(gateway.fields, {
'search': {'query': 'plan', 'kind': 'run', 'limit': 0},
});
expect(response, isNotNull);
expect(response!.query, 'plan');
expect(response.kind, SearchKind.run);
expect(response.results.single['target'], 'run:11');
expect(response.truncated, isTrue);
expect(response.scannedSteps, 27);
expect(response.scannedBytes, 4096);
expect(response.cap, 50);
expect(response.scanBoundBytes, 1048576);
},
);
test('all-kinds search still sends the empty kind field', () async {
final gateway = RecordingGateway()
..reply = {
'search_results': {'results': <JsonMap>[]},
};
await SearchRepository(gateway).search(query: 'plan', kind: SearchKind.all);
expect(gateway.fields, {
'search': {'query': 'plan', 'kind': '', 'limit': 0},
});
});
test(
'a reply without search_results is null, not an empty success',
() async {
final gateway = RecordingGateway()..reply = {'type': 'pong'};
final response = await SearchRepository(
gateway,
).search(query: 'plan', kind: SearchKind.all);
expect(response, isNull);
},
);
test('server refusals propagate to the caller unchanged', () async {
final gateway = RecordingGateway()
..failure = StateError('permission denied');
await expectLater(
SearchRepository(gateway).search(query: 'plan', kind: SearchKind.all),
throwsA(
isA<StateError>().having(
(error) => error.message,
'message',
'permission denied',
),
),
);
});
}
@@ -0,0 +1,161 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/search/domain/search_row.dart';
JsonMap pipelineHit([JsonMap overrides = const {}]) => {
'kind': 'pipeline',
'target': 'pipeline:7',
'pipeline': {
'id': 7,
'name': 'release',
'version': 3,
'stages': 4,
...overrides,
},
};
JsonMap versionHit() => {
'kind': 'version',
'target': 'pipeline:9:v2',
'recency': '2026-01-01T00:00:00Z',
'version': {
'pipeline_id': 9,
'version': 2,
'content_hash': 'abc',
'created_at': '2026-01-01T00:00:00Z',
},
};
JsonMap runHit([JsonMap overrides = const {}]) => {
'kind': 'run',
'target': 'run:11',
'run': {
'id': 11,
'pipeline_name': 'release',
'status': 'succeeded',
'created_at': '2026-01-01T00:00:00Z',
...overrides,
},
};
JsonMap stepHit([JsonMap overrides = const {}]) => {
'kind': 'step',
'target': 'run:11:4',
'step': {
'run_id': 11,
'sequence': 4,
'stage': 'builder',
'visit': 2,
'outcome': 'success',
...overrides,
},
};
JsonMap fieldHit([JsonMap overrides = const {}]) => {
'kind': 'field',
'target': 'run:11:4:output',
'matched_field': 'output',
'field': {
'run_id': 11,
'sequence': 4,
'field': 'output',
'snippet': 'the release is ready',
...overrides,
},
};
JsonMap artifactHit([JsonMap overrides = const {}]) => {
'kind': 'artifact',
'target': '/artifacts/11/4/notes.md',
'artifact': {
'run_id': 11,
'sequence': 4,
'name': 'notes.md',
'content_type': 'text/markdown',
'size_bytes': 2048,
...overrides,
},
};
void main() {
test('per-kind rows mirror the browser titles and secondary lines', () {
final pipeline = searchRowView(pipelineHit(), 'release');
expect(pipeline.title, 'release');
expect(pipeline.secondary, 'pipeline 7 · v3 · 4 stages');
expect(pipeline.kindLabel, 'Pipeline');
expect(pipeline.target, 'pipeline:7');
final blankName = searchRowView(pipelineHit({'name': ' '}), 'x');
expect(blankName.title, 'pipeline 7');
final version = searchRowView(versionHit(), 'release');
expect(version.title, 'pipeline 9 · v2');
expect(version.secondary, startsWith('content abc · '));
expect(version.recency, isNotNull);
final run = searchRowView(runHit(), 'release');
expect(run.title, 'run #11 · release');
expect(run.secondary, startsWith('succeeded · '));
expect(run.secondary.split(' · '), hasLength(2));
final unnamed = searchRowView(runHit({'pipeline_name': ''}), '');
expect(unnamed.title, 'run #11');
final step = searchRowView(stepHit({'target': '#success'}), '');
expect(step.title, 'run #11 · builder visit 2');
expect(step.secondary, 'success · → #success');
final artifact = searchRowView(artifactHit(), 'notes');
expect(artifact.title, 'notes.md');
expect(artifact.secondary, 'run #11 · step 4 · text/markdown · 2.0 KiB');
});
test('a field snippet marks the first case-insensitive query occurrence', () {
final row = searchRowView(fieldHit(), 'RELEASE');
expect(row.snippet, 'the release is ready');
expect(row.snippetSpans.map((span) => (span.text, span.matched)), [
('the ', false),
('release', true),
(' is ready', false),
]);
expect(row.snippetSpans.where((span) => span.matched), hasLength(1));
final absent = searchRowView(fieldHit({'snippet': 'no match'}), 'absent');
expect(absent.snippetSpans.single.matched, isFalse);
expect(absent.snippetSpans.single.text, 'no match');
final blank = searchRowView(fieldHit({'snippet': ''}), 'release');
expect(blank.snippetSpans, isEmpty);
});
test('unknown or targetless hits are read-only and never open a guess', () {
final unknown = searchRowView({
'kind': 'future_kind',
'target': 'widget:7',
}, 'x');
expect(unknown.title, 'widget:7');
expect(unknown.secondary, 'kind "future_kind" · read-only');
expect(unknown.openable, isFalse);
expect(unknown.target, isNull);
expect(unknown.kindLabel, 'Unrecognised result');
final targetless = searchRowView({
'kind': 'run',
'run': {'id': 11},
}, 'x');
expect(targetless.openable, isFalse);
expect(targetless.target, isNull);
expect(searchRowView(pipelineHit(), '').openable, isTrue);
expect(searchRowView(versionHit(), '').openable, isTrue);
expect(searchRowView(artifactHit(), '').openable, isTrue);
});
test('byte sizes use the shared binary rendering', () {
expect(humanBytes(0), '0 B');
expect(humanBytes(1023), '1023 B');
expect(humanBytes(1024), '1.0 KiB');
expect(humanBytes(2048), '2.0 KiB');
expect(humanBytes(1048576), '1.0 MiB');
});
}
@@ -0,0 +1,146 @@
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/search/search_screen.dart';
class RecordingGateway implements ApiGateway {
RecordingGateway(this.reply);
final JsonMap Function(String query, String kind) reply;
final calls = <JsonMap>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(Map.of(fields));
final search = Map<String, dynamic>.from(fields['search'] as Map);
return reply(search['query'] as String, search['kind'] as String);
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
JsonMap response(
List<JsonMap> results, {
bool truncated = false,
int scannedSteps = 2,
int scannedBytes = 128,
}) => {
'search_results': {
'results': results,
'truncated': truncated,
'scanned_steps': scannedSteps,
'scanned_bytes': scannedBytes,
'cap': 50,
'scan_bound_bytes': 1 << 20,
},
};
final pipeline = {
'kind': 'pipeline',
'target': 'pipeline:7',
'pipeline': {'id': 7, 'name': 'Release planner', 'version': 3, 'stages': 4},
};
Widget material(Widget child) => MaterialApp(home: child);
void main() {
testWidgets(
'a fresh screen sends no request and idle is not an empty result',
(tester) async {
final gateway = RecordingGateway((_, _) => response([pipeline]));
await tester.pumpWidget(
material(SearchScreen(gateway: gateway, onOpen: (_) {})),
);
expect(gateway.calls, isEmpty);
expect(
find.text('Search pipelines, runs and artifacts.'),
findsOneWidget,
);
expect(find.textContaining('No matches'), findsNothing);
},
);
testWidgets('an empty server result shows the query-specific empty copy', (
tester,
) async {
final gateway = RecordingGateway((_, _) => response(const []));
await tester.pumpWidget(
material(SearchScreen(gateway: gateway, onOpen: (_) {})),
);
await tester.enterText(find.byKey(const ValueKey('search.field')), 'zzz');
await tester.pump(const Duration(milliseconds: 300));
await tester.pumpAndSettle();
expect(gateway.calls, hasLength(1));
expect(find.text('No matches for "zzz".'), findsOneWidget);
expect(find.text('Searching…'), findsNothing);
});
testWidgets(
'a truncated empty reply keeps the server scan warning on screen',
(tester) async {
final gateway = RecordingGateway(
(_, _) => response(
const [],
truncated: true,
scannedSteps: 2000,
scannedBytes: 1048576,
),
);
await tester.pumpWidget(
material(SearchScreen(gateway: gateway, onOpen: (_) {})),
);
await tester.enterText(
find.byKey(const ValueKey('search.field')),
'needle',
);
await tester.pump(const Duration(milliseconds: 300));
await tester.pumpAndSettle();
expect(
find.text('No matches for "needle" within the server\'s scan limit.'),
findsOneWidget,
);
expect(find.textContaining('Results truncated'), findsOneWidget);
expect(find.textContaining('scanned 2000 steps'), findsOneWidget);
expect(find.textContaining('scan limit 1.0 MiB'), findsOneWidget);
},
);
testWidgets('changing Kind clears a typed token and requests the new kind', (
tester,
) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final gateway = RecordingGateway((_, _) => response([pipeline]));
await tester.pumpWidget(
material(SearchScreen(gateway: gateway, onOpen: (_) {})),
);
await tester.enterText(
find.byKey(const ValueKey('search.field')),
'plan t:run',
);
await tester.pump(const Duration(milliseconds: 300));
await tester.pumpAndSettle();
expect((gateway.calls.single['search'] as Map)['kind'], 'run');
await tester.tap(find.byKey(const ValueKey('search.kind')));
await tester.pumpAndSettle();
await tester.tap(find.text('Pipelines').last);
await tester.pumpAndSettle();
final field = tester.widget<SearchBar>(
find.byKey(const ValueKey('search.field')),
);
expect(field.controller!.text.trim(), 'plan');
expect(field.controller!.text, isNot(contains('t:run')));
expect((gateway.calls.last['search'] as Map)['kind'], 'pipeline');
});
}
@@ -0,0 +1,223 @@
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/search/domain/search_models.dart';
import 'package:pipelines_app/features/search/search_screen.dart';
class ImmediateGateway implements ApiGateway {
ImmediateGateway(this.reply);
final JsonMap Function(String query, String kind) reply;
final calls = <JsonMap>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(Map.of(fields));
final search = Map<String, dynamic>.from(fields['search'] as Map);
return reply(search['query'] as String, search['kind'] as String);
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
class FailingThenSucceedingGateway implements ApiGateway {
FailingThenSucceedingGateway(this.success);
final JsonMap success;
var calls = 0;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls++;
if (calls == 1) throw StateError('unknown command: search');
return success;
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
JsonMap hit({
required String kind,
required String target,
required Map<String, dynamic> payload,
}) => {'kind': kind, 'target': target, ...payload};
JsonMap response(List<JsonMap> results) => {
'search_results': {
'results': results,
'truncated': false,
'scanned_steps': 4,
'scanned_bytes': 512,
'cap': 50,
'scan_bound_bytes': 1 << 20,
},
};
final pipeline = hit(
kind: 'pipeline',
target: 'pipeline:7',
payload: {
'pipeline': {'id': 7, 'name': 'Release planner', 'version': 3, 'stages': 4},
},
);
final field = hit(
kind: 'field',
target: 'run:11:4:output',
payload: {
'matched_field': 'output',
'field': {
'run_id': 11,
'sequence': 4,
'field': 'output',
'snippet': 'the release is ready',
},
},
);
void useNarrowSurface(WidgetTester tester) {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
}
Widget largeText(Widget child) => MediaQuery(
data: const MediaQueryData(textScaler: TextScaler.linear(2)),
child: child,
);
Future<void> search(WidgetTester tester, String query) async {
await tester.enterText(find.byKey(const ValueKey('search.field')), query);
await tester.pump(const Duration(milliseconds: 300));
await tester.pumpAndSettle();
}
void main() {
for (final width in [390.0, 1000.0]) {
testWidgets(
'Material search is native and usable at width $width and 2x text',
(tester) async {
useNarrowSurface(tester);
tester.view.physicalSize = Size(width, 844);
final gateway = ImmediateGateway((_, _) => response([pipeline, field]));
JsonMap? opened;
await tester.pumpWidget(
MaterialApp(
home: largeText(
SearchScreen(
gateway: gateway,
onOpen: (value) => opened = value,
cupertino: false,
),
),
),
);
expect(find.byType(SearchBar), findsOneWidget);
expect(find.byType(DropdownButton<SearchKind>), findsOneWidget);
expect(find.text('All kinds'), findsOneWidget);
expect(gateway.calls, isEmpty);
await search(tester, 'release');
expect(gateway.calls.single, {
'search': {'query': 'release', 'kind': '', 'limit': 0},
});
expect(find.text('Release planner'), findsOneWidget);
expect(find.textContaining('the release is ready'), findsOneWidget);
expect(find.textContaining('4 results'), findsNothing);
expect(tester.takeException(), isNull);
await tester.tap(
find.byKey(const ValueKey('search.result.pipeline:7')),
);
expect(opened?['target'], 'pipeline:7');
expect(opened?['kind'], 'pipeline');
},
);
}
testWidgets(
'Cupertino search uses native controls and opens the real target',
(tester) async {
useNarrowSurface(tester);
final gateway = ImmediateGateway((_, _) => response([pipeline]));
JsonMap? opened;
await tester.pumpWidget(
CupertinoApp(
home: largeText(
SearchScreen(
gateway: gateway,
onOpen: (value) => opened = value,
cupertino: true,
),
),
),
);
expect(find.byType(CupertinoSearchTextField), findsOneWidget);
await search(tester, 'release');
expect(find.text('Release planner'), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.tap(find.byKey(const ValueKey('search.result.pipeline:7')));
expect(opened?['target'], 'pipeline:7');
},
);
testWidgets('a read-only hit cannot be opened', (tester) async {
useNarrowSurface(tester);
final unknown = hit(
kind: 'future_kind',
target: 'widget:7',
payload: const {},
);
final gateway = ImmediateGateway((_, _) => response([unknown]));
JsonMap? opened;
await tester.pumpWidget(
MaterialApp(
home: SearchScreen(
gateway: gateway,
onOpen: (value) => opened = value,
cupertino: false,
),
),
);
await search(tester, 'widget');
expect(find.textContaining('read-only'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('search.result.widget:7')));
expect(opened, isNull);
});
testWidgets('an unsupported server shows its sentence and retry recovers', (
tester,
) async {
useNarrowSurface(tester);
final gateway = FailingThenSucceedingGateway(response([pipeline]));
await tester.pumpWidget(
MaterialApp(
home: SearchScreen(gateway: gateway, onOpen: (_) {}, cupertino: false),
),
);
await search(tester, 'release');
expect(
find.text(
'This server does not support search. Update the Pipelines server, then try again.',
),
findsOneWidget,
);
expect(find.byKey(const ValueKey('search.retry')), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('search.retry')));
await tester.pumpAndSettle();
expect(gateway.calls, 2);
expect(find.text('Release planner'), findsOneWidget);
expect(find.byKey(const ValueKey('search.retry')), findsNothing);
});
}
@@ -0,0 +1,50 @@
import 'dart:async';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/search/data/search_repository.dart';
import 'package:pipelines_app/features/search/domain/search_controller.dart';
class QueuedGateway implements ApiGateway {
final calls = <JsonMap>[];
final pending = <Completer<JsonMap>>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
calls.add(Map.of(fields));
final completer = Completer<JsonMap>();
pending.add(completer);
return completer.future;
}
@override
Stream<JsonMap> get frames => const Stream.empty();
void succeed(int index, JsonMap reply) => pending[index].complete(reply);
void fail(int index, Object error) => pending[index].completeError(error);
JsonMap get lastSearch =>
Map<String, dynamic>.from((calls.last['search'] as Map));
}
JsonMap envelope(
List<JsonMap> results, {
bool truncated = false,
int scannedSteps = 0,
int scannedBytes = 0,
int cap = 50,
int scanBoundBytes = 1 << 20,
}) => {
'search_results': {
'results': results,
'truncated': truncated,
'scanned_steps': scannedSteps,
'scanned_bytes': scannedBytes,
'cap': cap,
'scan_bound_bytes': scanBoundBytes,
},
};
OmniSearchController controllerFor(ApiGateway gateway) => OmniSearchController(
repository: SearchRepository(gateway),
debounce: Duration.zero,
);
@@ -0,0 +1,115 @@
import 'dart:async';
import 'dart:convert';
import 'package:web_socket_channel/web_socket_channel.dart';
/// A deterministic websocket channel for the Settings tests. It records every
/// outgoing request and lets the test complete readiness and deliver replies.
class FakeChannel implements WebSocketChannel {
FakeChannel(this.uri);
final Uri uri;
final StreamController<dynamic> incoming = StreamController<dynamic>();
final List<String> outgoing = <String>[];
final Completer<void> readyCompleter = Completer<void>();
bool _closed = false;
void markReady() {
if (!readyCompleter.isCompleted) readyCompleter.complete();
}
void reply(Map<String, dynamic> message) {
if (!incoming.isClosed) incoming.add(jsonEncode(message));
}
void fail(String message) {
if (!incoming.isClosed) incoming.addError(StateError(message));
}
void closeStream() {
if (!incoming.isClosed) {
_closed = true;
incoming.close();
}
}
List<Map<String, dynamic>> get decodedOutgoing => outgoing
.map((item) => jsonDecode(item) as Map<String, dynamic>)
.toList(growable: false);
@override
Stream<dynamic> get stream => incoming.stream;
@override
WebSocketSink get sink => _FakeSink(this);
@override
Future<void> get ready => readyCompleter.future;
@override
String? get protocol => null;
@override
int? get closeCode => _closed ? 1000 : null;
@override
String? get closeReason => null;
@override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _FakeSink implements WebSocketSink {
_FakeSink(this.channel);
final FakeChannel channel;
@override
void add(dynamic event) {
if (event is String) channel.outgoing.add(event);
}
@override
void addError(Object error, [StackTrace? stackTrace]) => throw error;
@override
Future<void> addStream(Stream<dynamic> stream) async {
await for (final item in stream) {
add(item);
}
}
@override
Future<void> close([int? closeCode, String? closeReason]) async {
channel.closeStream();
}
@override
Future<void> get done async {}
@override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
/// Records every channel the client asks for, so tests can prove that a rebuild
/// or an invalid URL opened no socket at all.
class FakeChannelFactory {
final List<FakeChannel> channels = <FakeChannel>[];
final List<Uri> uris = <Uri>[];
FakeChannel get last => channels.last;
WebSocketChannel call(Uri uri) {
uris.add(uri);
final channel = FakeChannel(uri);
channels.add(channel);
return channel;
}
}
/// Let queued microtasks (state events, request sends, replies) run.
Future<void> settle() async {
for (var i = 0; i < 4; i++) {
await Future<void>.delayed(Duration.zero);
}
}
@@ -0,0 +1,440 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart'
as transport;
import 'package:pipelines_app/features/settings/settings_controller.dart';
import 'package:pipelines_app/features/settings/settings_copy.dart';
import 'package:pipelines_app/features/settings/settings_store.dart';
import 'fake_channel.dart';
void main() {
test('initializes without opening a connection', () async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
final controller = SettingsController(
client: client,
store: MemorySettingsStore(
serverUrl: 'ws://saved.test/connect',
workspace: '/srv/pipelines',
),
);
addTearDown(controller.dispose);
await controller.initialize();
await settle();
expect(controller.serverUrl, 'ws://saved.test/connect');
expect(controller.workspaceDraft, '/srv/pipelines');
expect(controller.savedWorkspace, '/srv/pipelines');
expect(factory.channels, isEmpty);
expect(controller.connectionLines, <String>['Not connected']);
});
test(
'an initial endpoint seeds the draft but is not persisted by itself',
() async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
final store = MemorySettingsStore(serverUrl: 'ws://saved.test/connect');
final controller = SettingsController(
client: client,
store: store,
initialEndpoint: Uri.parse('ws://initial.test:9000'),
);
addTearDown(controller.dispose);
await controller.initialize();
expect(controller.serverUrl, 'ws://initial.test:9000');
expect(store.serverUrl, 'ws://saved.test/connect');
},
);
test('a native/default endpoint seeds an empty store', () async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
final controller = SettingsController(
client: client,
store: MemorySettingsStore(),
defaultEndpoint: 'ws://page.test/connect',
);
addTearDown(controller.dispose);
await controller.initialize();
expect(controller.serverUrl, 'ws://page.test/connect');
});
test('an invalid URL names the field error and opens no socket', () async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
final store = MemorySettingsStore();
final controller = SettingsController(client: client, store: store);
addTearDown(controller.dispose);
await controller.initialize();
controller.updateServerUrl('http://example.test');
await controller.connect();
await settle();
expect(controller.urlError, contains('Unsupported scheme'));
expect(factory.channels, isEmpty);
expect(store.serverUrl, '');
});
test('a URL with credentials is rejected before it is persisted', () async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
final store = MemorySettingsStore();
final controller = SettingsController(client: client, store: store);
addTearDown(controller.dispose);
await controller.initialize();
controller.updateServerUrl('ws://operator:secret@example.test/connect');
await controller.connect();
await settle();
expect(controller.urlError, contains('Credentials are not supported'));
expect(factory.channels, isEmpty);
expect(store.serverUrl, '');
});
test(
'connect validates, normalizes, persists and pings exactly once',
() async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
final store = MemorySettingsStore();
final controller = SettingsController(client: client, store: store);
await controller.initialize();
controller.updateServerUrl(' ws://example.test:8123 ');
final connecting = controller.connect();
await settle();
expect(factory.uris.single.toString(), 'ws://example.test:8123/connect');
expect(controller.serverUrl, 'ws://example.test:8123/connect');
expect(store.serverUrl, 'ws://example.test:8123/connect');
factory.last.markReady();
await connecting;
await settle();
final outgoing = factory.last.decodedOutgoing;
expect(outgoing, hasLength(1));
expect(outgoing.single['type'], 'ping');
expect(controller.connection.kind, transport.ConnectionKind.connected);
factory.last.reply(<String, dynamic>{
'id': outgoing.single['id'],
'type': 'pong',
'build': <String, dynamic>{'version': 'v9', 'commit': 'deadbee'},
'time': '2026-10-21T12:00:00Z',
});
await settle();
expect(controller.buildVersion, 'v9');
expect(controller.buildCommit, 'deadbee');
expect(controller.serverTime, '2026-10-21T12:00:00Z');
expect(controller.connectionLines, <String>[
'Connected',
'Server build v9 (deadbee)',
'Server time 2026-10-21T12:00:00Z',
]);
// Rebuilding or notifying must not send another ping for this connection.
await settle();
expect(factory.last.decodedOutgoing, hasLength(1));
controller.dispose();
await client.dispose();
},
);
test(
'the card is pending until the ping answers, then names missing values',
() async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
final reply = Completer<Map<String, dynamic>>();
final controller = SettingsController(
client: client,
store: MemorySettingsStore(),
ping: () => reply.future,
);
await controller.initialize();
controller.updateServerUrl('ws://example.test:8123');
final connecting = controller.connect();
await settle();
factory.last.markReady();
await connecting;
await settle();
expect(controller.pingInFlight, isTrue);
expect(controller.connectionLines, <String>[
'Connected',
serverDetailsPending,
]);
reply.complete(<String, dynamic>{'type': 'pong'});
await settle();
expect(controller.pingInFlight, isFalse);
expect(controller.connectionLines, <String>[
'Connected',
'Server build unavailable',
'Server time unavailable',
]);
controller.dispose();
await client.dispose();
},
);
test(
'a ping failure is one explicit line, not two unavailable values',
() async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
final controller = SettingsController(
client: client,
store: MemorySettingsStore(),
ping: () async => throw StateError('probe failed'),
);
await controller.initialize();
controller.updateServerUrl('ws://example.test:8123');
final connecting = controller.connect();
await settle();
factory.last.markReady();
await connecting;
await settle();
expect(controller.pingError, startsWith('Server details unavailable:'));
expect(controller.pingError, contains('probe failed'));
expect(controller.pingInFlight, isFalse);
expect(controller.connectionLines, <Object>[
'Connected',
startsWith('Server details unavailable:'),
]);
expect(controller.connection.kind, transport.ConnectionKind.connected);
controller.dispose();
await client.dispose();
},
);
test(
'disconnect clears server details and leaves the shared client alive',
() async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
final controller = SettingsController(
client: client,
store: MemorySettingsStore(),
);
await controller.initialize();
controller.updateServerUrl('ws://example.test:8123');
final connecting = controller.connect();
await settle();
factory.last.markReady();
await connecting;
await settle();
factory.last.reply(<String, dynamic>{
'id': factory.last.decodedOutgoing.single['id'],
'type': 'pong',
'build': <String, dynamic>{'version': 'v9'},
'time': '2026-10-21T12:00:00Z',
});
await settle();
expect(controller.buildVersion, 'v9');
await controller.disconnect();
await settle();
expect(controller.connection.kind, transport.ConnectionKind.idle);
expect(controller.buildVersion, '');
expect(controller.serverTime, '');
expect(controller.connectionLines, <String>['Not connected']);
controller.dispose();
await client.dispose();
},
);
test('reconnect opens one new connection after a disconnect', () async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
final controller = SettingsController(
client: client,
store: MemorySettingsStore(),
);
await controller.initialize();
controller.updateServerUrl('ws://example.test:8123');
final connecting = controller.connect();
await settle();
factory.last.markReady();
await connecting;
await controller.disconnect();
await settle();
final reconnecting = controller.reconnect();
await settle();
expect(factory.channels, hasLength(2));
factory.last.markReady();
await reconnecting;
await settle();
expect(controller.connection.kind, transport.ConnectionKind.connected);
controller.dispose();
await client.dispose();
});
test(
'disposing the screen does not dispose or disconnect the shared client',
() async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
final controller = SettingsController(
client: client,
store: MemorySettingsStore(),
);
await controller.initialize();
controller.updateServerUrl('ws://example.test:8123');
final connecting = controller.connect();
await settle();
factory.last.markReady();
await connecting;
await settle();
controller.dispose();
await settle();
expect(
client.state.kind,
transport.ConnectionKind.connected,
reason: 'the feature must not disconnect a client it does not own',
);
await client.dispose();
},
);
test('opening while already connected pings that connection once', () async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
final connecting = client.connect(Uri.parse('ws://example.test:8123'));
await settle();
factory.last.markReady();
await connecting;
await settle();
expect(factory.last.outgoing, isEmpty);
final controller = SettingsController(
client: client,
store: MemorySettingsStore(),
);
await controller.initialize();
await settle();
expect(factory.last.decodedOutgoing, hasLength(1));
expect(factory.last.decodedOutgoing.single['type'], 'ping');
controller.dispose();
await client.dispose();
});
test(
'a failed endpoint write still connects but says it is session-only',
() async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
final store = MemorySettingsStore()..failSaves = true;
final controller = SettingsController(client: client, store: store);
await controller.initialize();
controller.updateServerUrl('ws://example.test:8123');
final connecting = controller.connect();
await settle();
expect(factory.channels, hasLength(1));
expect(store.serverUrl, '');
expect(controller.endpointSaveError, isNotEmpty);
factory.last.markReady();
await connecting;
await settle();
expect(controller.connection.kind, transport.ConnectionKind.connected);
controller.dispose();
await client.dispose();
},
);
test('a dropped connection exposes the reason and retry backoff', () async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
final controller = SettingsController(
client: client,
store: MemorySettingsStore(),
);
await controller.initialize();
controller.updateServerUrl('ws://example.test:8123');
final connecting = controller.connect();
await settle();
factory.last.markReady();
await connecting;
await settle();
factory.last.fail('socket gone');
await settle();
expect(controller.connection.kind, transport.ConnectionKind.disconnected);
expect(controller.connection.reason, contains('socket gone'));
expect(controller.connection.retrying, isTrue);
expect(
controller.connectionLines,
containsAll(<String>['Disconnected', 'Retrying with backoff\u2026']),
);
// Cancel the client's scheduled retry before the test ends.
await client.disconnect();
controller.dispose();
await client.dispose();
});
test(
'workspace save persists only an absolute path and reports failures',
() async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
final store = MemorySettingsStore();
final controller = SettingsController(client: client, store: store);
await controller.initialize();
controller.updateWorkspace('relative/path');
expect(controller.workspaceError, workspacePathError);
await controller.saveWorkspace();
expect(store.workspace, '');
expect(controller.savedWorkspace, '');
controller.updateWorkspace(' /srv/pipelines ');
await controller.saveWorkspace();
expect(store.workspace, '/srv/pipelines');
expect(controller.savedWorkspace, '/srv/pipelines');
expect(controller.workspaceDraft, '/srv/pipelines');
store.failSaves = true;
controller.updateWorkspace('/other/path');
await controller.saveWorkspace();
expect(controller.savedWorkspace, '/srv/pipelines');
expect(controller.workspaceSaveError, isNotEmpty);
controller.dispose();
await client.dispose();
},
);
}
@@ -0,0 +1,160 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart'
as transport;
import 'package:pipelines_app/features/settings/default_endpoint.dart';
import 'package:pipelines_app/features/settings/settings_copy.dart';
void main() {
group('workspace validation', () {
test('blank is untouched, relative is rejected, absolute is accepted', () {
expect(validateWorkspacePath(''), isNull);
expect(validateWorkspacePath(' '), isNull);
expect(validateWorkspacePath('repos/pipelines'), workspacePathError);
expect(validateWorkspacePath('/Users/you/repos/pipelines'), isNull);
expect(
validateWorkspacePath(' /srv/pipelines '),
isNull,
reason: 'trimmed before validating',
);
});
test('Save needs a trimmed absolute path, never a blank field', () {
expect(canSaveWorkspace(''), isFalse);
expect(canSaveWorkspace(' '), isFalse);
expect(canSaveWorkspace('relative/path'), isFalse);
expect(canSaveWorkspace('/srv/pipelines'), isTrue);
expect(canSaveWorkspace(' /srv/pipelines '), isTrue);
});
test('the saved line names an empty value instead of showing nothing', () {
expect(savedWorkspaceLine(''), 'Saved workspace: (none)');
expect(
savedWorkspaceLine(' /srv/pipelines '),
'Saved workspace: /srv/pipelines',
);
});
});
group('server build and connection card', () {
test('build label includes only the reported parts', () {
expect(serverBuildLabel(), '');
expect(serverBuildLabel(version: 'v1.2.3'), 'Server build v1.2.3');
expect(
serverBuildLabel(version: 'v1.2.3', commit: 'abc1234'),
'Server build v1.2.3 (abc1234)',
);
expect(serverBuildLabel(commit: 'abc1234'), 'Server build (abc1234)');
});
test('idle, connecting and disconnected states keep the app words', () {
expect(
connectionCardLines(
const transport.ConnectionState(transport.ConnectionKind.idle),
),
<String>['Not connected'],
);
expect(
connectionCardLines(
const transport.ConnectionState(
transport.ConnectionKind.connecting,
attempt: 3,
),
),
<String>['Connecting (attempt 3)\u2026'],
);
expect(
connectionCardLines(
const transport.ConnectionState(
transport.ConnectionKind.disconnected,
reason: 'Connection closed',
retrying: true,
),
),
<String>[
'Disconnected',
'Connection closed',
'Retrying with backoff\u2026',
],
);
expect(
connectionCardLines(
const transport.ConnectionState(
transport.ConnectionKind.disconnected,
),
),
<String>['Disconnected'],
);
});
test('connected names unavailable build/time instead of zero', () {
final lines = connectionCardLines(
const transport.ConnectionState(transport.ConnectionKind.connected),
);
expect(lines, <String>[
'Connected',
'Server build unavailable',
'Server time unavailable',
]);
});
test('connected reports the ping fields and an explicit ping error', () {
final lines = connectionCardLines(
const transport.ConnectionState(transport.ConnectionKind.connected),
buildVersion: 'v9',
buildCommit: 'deadbee',
serverTime: '2026-10-21T12:00:00Z',
pingError: 'Server details unavailable: timed out',
);
expect(lines, <String>[
'Connected',
'Server build v9 (deadbee)',
'Server time 2026-10-21T12:00:00Z',
'Server details unavailable: timed out',
]);
});
test(
'connected while the ping is pending says loading, not unavailable',
() {
final lines = connectionCardLines(
const transport.ConnectionState(transport.ConnectionKind.connected),
pingInFlight: true,
);
expect(lines, <String>['Connected', serverDetailsPending]);
expect(lines.any((line) => line.contains('unavailable')), isFalse);
},
);
test('a failed ping is one explicit line, not two unavailable values', () {
final lines = connectionCardLines(
const transport.ConnectionState(transport.ConnectionKind.connected),
pingError: 'Server details unavailable: timed out',
);
expect(lines, <String>[
'Connected',
'Server details unavailable: timed out',
]);
});
});
group('same-origin default endpoint', () {
test('native builds bake no endpoint', () {
expect(defaultServerUrl(web: false), '');
});
test('web uses the page origin, upgraded to ws/wss', () {
expect(
defaultServerUrl(web: true, base: Uri.parse('http://127.0.0.1:8123/')),
'ws://127.0.0.1:8123/connect',
);
expect(
defaultServerUrl(
web: true,
base: Uri.parse('https://pipelines.example.test/pipelines'),
),
'wss://pipelines.example.test/connect',
);
expect(defaultServerUrl(web: true, base: Uri.parse('about:blank')), '');
});
});
}
@@ -0,0 +1,63 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/settings/settings_controller.dart';
import 'package:pipelines_app/features/settings/settings_store.dart';
import 'fake_channel.dart';
class _DelayedStore extends MemorySettingsStore {
final loaded = Completer<SettingsValues>();
@override
Future<SettingsValues> load() => loaded.future;
}
void main() {
test(
'connected first frame loads details before preferences finish',
() async {
final factory = FakeChannelFactory();
final client = PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
final connected = client.connect(Uri.parse('ws://fixture.test/connect'));
await settle();
factory.last.markReady();
await connected;
final store = _DelayedStore();
final pong = Completer<Map<String, dynamic>>();
var pings = 0;
final controller = SettingsController(
client: client,
store: store,
ping: () {
pings++;
return pong.future;
},
);
addTearDown(controller.dispose);
expect(controller.connectionLines, [
'Connected',
'Loading server details…',
]);
final initializing = controller.initialize();
expect(controller.pingInFlight, isTrue);
expect(pings, 1);
store.loaded.complete(const SettingsValues());
await initializing;
expect(pings, 1);
await client.disconnect();
await settle();
pong.complete({
'type': 'pong',
'build': {'version': 'stale'},
});
await settle();
expect(controller.connectionLines, ['Not connected']);
expect(controller.buildVersion, isEmpty);
},
);
}
@@ -0,0 +1,314 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart'
as transport;
import 'package:pipelines_app/features/settings/settings_copy.dart';
import 'package:pipelines_app/features/settings/settings_keys.dart';
import 'package:pipelines_app/features/settings/settings_screen.dart';
import 'package:pipelines_app/features/settings/settings_store.dart';
import 'fake_channel.dart';
void main() {
testWidgets('renders idle settings without opening a connection', (
tester,
) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
await _pump(
tester,
client,
store: MemorySettingsStore(
serverUrl: 'ws://saved.test/connect',
workspace: '/srv/pipelines',
),
);
expect(find.text('Settings'), findsOneWidget);
expect(find.text('Connection'), findsOneWidget);
expect(find.text('Workspace'), findsOneWidget);
expect(find.text('Not connected'), findsOneWidget);
expect(find.text('Saved workspace: /srv/pipelines'), findsOneWidget);
expect(
tester.widget<TextField>(find.byType(TextField).first).controller?.text,
'ws://saved.test/connect',
);
expect(find.byKey(SettingsKeys.connect), findsOneWidget);
expect(find.byKey(SettingsKeys.reconnect), findsOneWidget);
await tester.pump();
expect(factory.channels, isEmpty);
});
testWidgets('an invalid URL shows the field error and opens no socket', (
tester,
) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
await _pump(tester, client);
await tester.enterText(find.byType(TextField).first, 'http://example.test');
await tester.pump();
await tester.tap(find.byKey(SettingsKeys.connect));
await tester.pump();
await tester.pump();
expect(find.textContaining('Unsupported scheme'), findsOneWidget);
expect(factory.channels, isEmpty);
});
testWidgets('connect pings once and shows the reported build and time', (
tester,
) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
await _pump(tester, client);
await tester.enterText(
find.byType(TextField).first,
'ws://example.test:8123',
);
await tester.pump();
await tester.tap(find.byKey(SettingsKeys.connect));
await tester.pump();
await tester.pump();
expect(factory.channels, hasLength(1));
expect(factory.uris.single.toString(), 'ws://example.test:8123/connect');
expect(find.text('Connecting (attempt 1)\u2026'), findsOneWidget);
factory.last.markReady();
await tester.pump();
await tester.pump();
final outgoing = factory.last.decodedOutgoing;
expect(outgoing, hasLength(1));
expect(outgoing.single['type'], 'ping');
factory.last.reply(<String, dynamic>{
'id': outgoing.single['id'],
'type': 'pong',
'build': <String, dynamic>{'version': 'v9', 'commit': 'deadbee'},
'time': '2026-10-21T12:00:00Z',
});
await tester.pump();
await tester.pump();
expect(find.text('Connected'), findsOneWidget);
expect(find.text('Server build v9 (deadbee)'), findsOneWidget);
expect(find.text('Server time 2026-10-21T12:00:00Z'), findsOneWidget);
expect(find.byKey(SettingsKeys.disconnect), findsOneWidget);
expect(find.byKey(SettingsKeys.connect), findsOneWidget);
expect(factory.last.decodedOutgoing, hasLength(1));
});
testWidgets('connected without a ping reply names unavailable values', (
tester,
) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
await _pump(tester, client);
await tester.enterText(
find.byType(TextField).first,
'ws://example.test:8123',
);
await tester.pump();
await tester.tap(find.byKey(SettingsKeys.connect));
await tester.pump();
await tester.pump();
factory.last.markReady();
await tester.pump();
await tester.pump();
expect(factory.last.decodedOutgoing.single['type'], 'ping');
expect(find.text('Connected'), findsOneWidget);
expect(find.text(serverDetailsPending), findsOneWidget);
expect(find.text('Server build unavailable'), findsNothing);
factory.last.reply(<String, dynamic>{
'id': factory.last.decodedOutgoing.single['id'],
'type': 'pong',
});
await tester.pump();
await tester.pump();
expect(find.text(serverDetailsPending), findsNothing);
expect(find.text('Server build unavailable'), findsOneWidget);
expect(find.text('Server time unavailable'), findsOneWidget);
});
testWidgets(
'workspace validation gates Save and only a save updates the line',
(tester) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
final store = MemorySettingsStore();
await _pump(tester, client, store: store);
final workspace = find.byType(TextField).at(1);
await tester.enterText(workspace, 'relative/path');
await tester.pump();
expect(find.textContaining('must be an absolute path'), findsOneWidget);
expect(
tester
.widget<FilledButton>(find.byKey(SettingsKeys.saveWorkspace))
.onPressed,
isNull,
);
expect(find.text('Saved workspace: (none)'), findsOneWidget);
await tester.enterText(workspace, ' /srv/pipelines ');
await tester.pump();
await tester.tap(find.byKey(SettingsKeys.saveWorkspace));
await tester.pump();
await tester.pump();
expect(find.text('Saved workspace: /srv/pipelines'), findsOneWidget);
expect(store.workspace, '/srv/pipelines');
},
);
testWidgets('iOS uses Cupertino fields, buttons and navigation', (
tester,
) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
await _pump(tester, client, platform: TargetPlatform.iOS);
expect(find.byType(CupertinoNavigationBar), findsOneWidget);
expect(find.byType(CupertinoTextField), findsNWidgets(2));
expect(find.byType(TextField), findsNothing);
expect(find.byType(FilledButton), findsNothing);
expect(find.byKey(SettingsKeys.connect), findsOneWidget);
expect(find.text('Trusted LAN/VPN only'), findsOneWidget);
});
testWidgets('narrow window with large text scrolls without overflow', (
tester,
) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
await _pump(tester, client, textScale: 2, size: const Size(320, 640));
expect(tester.takeException(), isNull);
await tester.scrollUntilVisible(
find.byKey(SettingsKeys.saveWorkspace),
200,
scrollable: find.byType(Scrollable).first,
);
expect(find.byKey(SettingsKeys.saveWorkspace), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('large text keeps the full labels and supporting copy', (
tester,
) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
await _pump(tester, client, textScale: 2, size: const Size(320, 640));
expect(find.text('Workspace path (on the server)'), findsOneWidget);
expect(find.text('Server URL'), findsOneWidget);
for (final copy in <String>[
'Workspace path (on the server)',
serverUrlHelper,
workspaceHelper,
]) {
final text = tester.widget<Text>(find.text(copy));
expect(text.maxLines, isNull, reason: 'no line cap on $copy');
final paragraph = tester.renderObject<RenderParagraph>(find.text(copy));
expect(
paragraph.didExceedMaxLines,
isFalse,
reason: 'the whole copy is laid out for $copy',
);
}
expect(tester.takeException(), isNull);
});
testWidgets('the text fields expose their labels to accessibility', (
tester,
) async {
final handle = tester.ensureSemantics();
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
await _pump(tester, client);
final labels = <String>[
tester
.getSemantics(find.byType(TextField).at(0))
.getSemanticsData()
.label,
tester
.getSemantics(find.byType(TextField).at(1))
.getSemanticsData()
.label,
];
expect(labels[0], contains('Server URL'));
expect(labels[1], contains('Workspace path (on the server)'));
handle.dispose();
});
testWidgets('unmounting leaves the shared client usable', (tester) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
await _pump(tester, client);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
final connecting = client.connect(Uri.parse('ws://example.test:8123'));
await tester.pump();
expect(factory.channels, hasLength(1));
factory.last.markReady();
await tester.pump();
await connecting;
});
}
Future<void> _pump(
WidgetTester tester,
transport.PipelinesClient client, {
SettingsStore? store,
TargetPlatform platform = TargetPlatform.android,
double textScale = 1,
Size size = const Size(800, 1200),
}) async {
await tester.binding.setSurfaceSize(size);
addTearDown(() => tester.binding.setSurfaceSize(null));
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: platform),
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child ?? const SizedBox.shrink(),
),
home: SettingsScreen(
client: client,
store: store ?? MemorySettingsStore(),
),
),
);
await tester.pump();
await tester.pump();
}
@@ -0,0 +1,68 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/settings/settings_store.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
SharedPreferences.setMockInitialValues(<String, Object>{});
});
test('starts blank when nothing is stored', () async {
const store = SharedPreferencesSettingsStore();
final values = await store.load();
expect(values.serverUrl, '');
expect(values.workspace, '');
});
test('writes only the feature-owned pipelines.next keys', () async {
const store = SharedPreferencesSettingsStore();
expect(await store.saveServerUrl(' ws://127.0.0.1:8081/connect '), isTrue);
expect(await store.saveWorkspace(' /srv/pipelines '), isTrue);
final preferences = await SharedPreferences.getInstance();
expect(
preferences.getString(settingsServerUrlKey),
'ws://127.0.0.1:8081/connect',
);
expect(preferences.getString(settingsWorkspaceKey), '/srv/pipelines');
expect(preferences.getKeys(), <String>{
settingsServerUrlKey,
settingsWorkspaceKey,
});
expect(settingsServerUrlKey, startsWith('pipelines.next.'));
expect(settingsWorkspaceKey, startsWith('pipelines.next.'));
final reloaded = await store.load();
expect(reloaded.serverUrl, 'ws://127.0.0.1:8081/connect');
expect(reloaded.workspace, '/srv/pipelines');
});
test('never reads or writes legacy web/Android preference keys', () async {
SharedPreferences.setMockInitialValues(<String, Object>{
'pipelines.web.serverUrl.v2': 'ws://legacy.test/connect',
'pipelines.web.workspace.v1': '/legacy/workspace',
'server_url': 'ws://android.test/connect',
'workspace': '/android/workspace',
});
const store = SharedPreferencesSettingsStore();
final values = await store.load();
expect(values.serverUrl, '');
expect(values.workspace, '');
await store.saveServerUrl('ws://new.test/connect');
await store.saveWorkspace('/new/workspace');
final preferences = await SharedPreferences.getInstance();
expect(
preferences.getString('pipelines.web.serverUrl.v2'),
'ws://legacy.test/connect',
);
expect(
preferences.getString('pipelines.web.workspace.v1'),
'/legacy/workspace',
);
expect(preferences.getString('server_url'), 'ws://android.test/connect');
expect(preferences.getString('workspace'), '/android/workspace');
});
}
@@ -0,0 +1,147 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/templates/data/template_repository.dart';
import 'template_test_support.dart';
void main() {
test(
'validate sends the exact source and returns the server graph',
() async {
final graph = <String, dynamic>{
'stages': [
{'key': 'build', 'type': 'model'},
],
'unknown_graph_field': true,
};
final gateway = RecordingGateway([
{'type': 'validated', 'graph': graph},
]);
final result = await TemplateRepository(gateway).validate(source);
expect(gateway.calls.single.type, 'validate');
expect(gateway.calls.single.fields, {'source': source});
expect(gateway.calls.single.fields['source'], source);
expect(result, graph);
},
);
test(
'validate rejects a reply without a graph instead of faking success',
() async {
for (final reply in <JsonMap>[
<String, dynamic>{'type': 'validated'},
<String, dynamic>{'type': 'validated', 'graph': null},
]) {
final gateway = RecordingGateway([reply]);
await expectLater(
TemplateRepository(gateway).validate(source),
throwsA(
isA<TemplateRepositoryException>().having(
(error) => error.message,
'message',
'The server returned no graph.',
),
),
);
}
},
);
test('validate propagates a server refusal verbatim', () async {
const refusal = ServerRefusal('invalid stage "añadir": unknown key');
final gateway = RefusingGateway(refusal);
await expectLater(
TemplateRepository(gateway).validate(source),
throwsA(same(refusal)),
);
expect(gateway.calls, ['validate']);
});
test('submit refuses a blank name without sending anything', () async {
for (final name in ['', ' ', '\t\n']) {
final gateway = RecordingGateway([
{
'detail': {'id': 1},
},
]);
await expectLater(
TemplateRepository(gateway).submit(name, source),
throwsA(
isA<TemplateRepositoryException>().having(
(error) => error.message,
'message',
'Enter a pipeline name.',
),
),
);
expect(gateway.calls, isEmpty);
}
});
test(
'submit trims the name, preserves the source and is always create-only',
() async {
final detail = <String, dynamic>{
'id': 9,
'name': 'Release 2',
'version': 1,
};
final gateway = RecordingGateway([
{'type': 'submitted', 'detail': detail},
]);
final result = await TemplateRepository(
gateway,
).submit(' Release 2 ', source);
expect(gateway.calls.single.type, 'submit');
expect(gateway.calls.single.fields, {
'name': 'Release 2',
'source': source,
'create_only': true,
});
expect(gateway.calls.single.fields.keys, [
'name',
'source',
'create_only',
]);
expect(result, detail);
},
);
test(
'submit rejects a reply without a detail instead of faking success',
() async {
final gateway = RecordingGateway([
<String, dynamic>{'type': 'submitted'},
]);
await expectLater(
TemplateRepository(gateway).submit('Release', source),
throwsA(
isA<TemplateRepositoryException>().having(
(error) => error.message,
'message',
'The server returned no pipeline detail.',
),
),
);
},
);
test('submit propagates a server refusal verbatim', () async {
const refusal = ServerRefusal('a pipeline named "Release" already exists');
final gateway = RefusingGateway(refusal);
await expectLater(
TemplateRepository(gateway).submit(' Release ', source),
throwsA(same(refusal)),
);
expect(gateway.calls, ['submit']);
});
}

Some files were not shown because too many files have changed in this diff Show More