merge(app): land retry wiring in the native run detail

Conflicts: app/lib/features/runs/ui/run_detail_actions.dart.
Keep main's recorded-artifacts action and the retry branch's spaced,
render-gated Wrap: Rename, Retry, Cancel, then Recorded artifacts.
This commit is contained in:
2026-10-21 22:52:00 +01:00
56 changed files with 8712 additions and 69 deletions
@@ -0,0 +1,321 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart';
import '../domain/artifact_fixtures.dart';
enum _Platform { material, cupertino }
JsonMap _recorded(
String name, {
String url = '',
String contentType = 'text/csv',
int sizeBytes = 2048,
}) => artifact(
name,
url: url.isEmpty ? null : url,
contentType: contentType,
sizeBytes: sizeBytes,
);
/// Two visits of `review` record the same filename; the second visit also
/// records `notes.md`. `build` records one file.
List<JsonMap> _steps() => <JsonMap>[
step(
stage: 'build',
sequence: 1,
visit: 1,
artifacts: [_recorded('build.log', contentType: 'text/plain')],
),
step(
stage: 'review',
sequence: 2,
visit: 1,
artifacts: [
_recorded('result.csv'),
_recorded('notes.md', contentType: 'text/markdown'),
],
),
step(
stage: 'review',
sequence: 3,
visit: 2,
artifacts: [_recorded('result.csv', url: '/artifacts/1/2/result.csv')],
),
];
Future<void> _pumpGallery(
WidgetTester tester,
_Platform platform,
List<JsonMap> steps, {
String configuredEndpoint = '',
bool executing = false,
Future<bool> Function(Uri)? openExternal,
}) async {
final page = ArtifactGalleryPage(
steps: steps,
executing: executing,
configuredEndpoint: configuredEndpoint,
openExternal: openExternal ?? (_) async => true,
);
await tester.pumpWidget(
platform == _Platform.material
? MaterialApp(home: page)
: CupertinoApp(home: page),
);
await tester.pumpAndSettle();
}
Finder _inDialog(_Platform platform, String text) => find.descendant(
of: find.byType(
platform == _Platform.material ? AlertDialog : CupertinoAlertDialog,
),
matching: find.text(text),
);
void main() {
for (final platform in _Platform.values) {
testWidgets('${platform.name}: lists recorded groups and rows', (
tester,
) async {
await _pumpGallery(tester, platform, _steps());
expect(find.text('Artifacts · 4 recorded'), findsOneWidget);
expect(find.text('build · visit 1'), findsOneWidget);
expect(find.text('review · visit 1'), findsOneWidget);
expect(find.text('review · visit 2'), findsOneWidget);
expect(find.text('result.csv'), findsNWidgets(2));
expect(find.text('notes.md'), findsOneWidget);
expect(find.text('text/markdown · 2.0\u00a0KiB'), findsOneWidget);
});
testWidgets('${platform.name}: duplicate filename stays visit distinct', (
tester,
) async {
final steps = _steps();
await _pumpGallery(tester, platform, steps);
await tester.tap(find.text('result.csv').at(1));
await tester.pumpAndSettle();
final groups = artifactGroups(steps);
final visitTwo = groups.firstWhere(
(group) => group.stageKey == 'review' && group.visit == 2,
);
final list = tester.widget<ArtifactVisitList>(
find.byType(ArtifactVisitList),
);
expect(
list.selectedIdentity,
artifactVisitIdentity(visitTwo, visitTwo.artifacts.single),
);
expect(_inDialog(platform, 'review · visit 2'), findsOneWidget);
expect(_inDialog(platform, 'review · visit 1'), findsNothing);
expect(_inDialog(platform, 'Artifacts · 1 recorded'), findsOneWidget);
});
}
testWidgets('capture notes and partial label come from the visit step', (
tester,
) async {
await _pumpGallery(tester, _Platform.material, [
step(
stage: 'review',
visit: 1,
artifacts: [_recorded('result.csv'), _recorded('notes.md')],
skipped: 2,
truncated: 3,
),
]);
expect(
find.text('Artifacts · 2 recorded · partial capture'),
findsOneWidget,
);
await tester.tap(find.text('result.csv'));
await tester.pumpAndSettle();
expect(
_inDialog(_Platform.material, 'Artifacts · 2 recorded · partial capture'),
findsOneWidget,
);
expect(
_inDialog(_Platform.material, '2 files excluded from artifact capture.'),
findsOneWidget,
);
expect(
_inDialog(
_Platform.material,
'3 files omitted by artifact capture limits.',
),
findsOneWidget,
);
});
testWidgets('an unavailable capture never claims nothing was recorded', (
tester,
) async {
await _pumpGallery(tester, _Platform.material, [
step(stage: 'review', visit: 1, includeArtifacts: false),
]);
expect(find.text('Artifacts · capture unavailable'), findsOneWidget);
expect(find.text('No artifacts recorded for this run.'), findsNothing);
});
testWidgets('a recorded empty capture says nothing was recorded', (
tester,
) async {
await _pumpGallery(tester, _Platform.material, [
step(stage: 'review', visit: 1, artifacts: const []),
]);
expect(find.text('No artifacts recorded for this run.'), findsOneWidget);
expect(find.byType(ArtifactVisitList), findsNothing);
});
testWidgets('a page with no steps says so explicitly', (tester) async {
await _pumpGallery(tester, _Platform.material, const []);
expect(find.text('No steps recorded for this run.'), findsOneWidget);
});
testWidgets('Open uses the resolved recorded url only', (tester) async {
final opened = <Uri>[];
await _pumpGallery(
tester,
_Platform.material,
[
step(
stage: 'review',
visit: 1,
artifacts: [
_recorded('result.csv', url: '/artifacts/1/1/result.csv'),
],
),
],
configuredEndpoint: 'ws://127.0.0.1:8081/connect',
openExternal: (uri) async {
opened.add(uri);
return true;
},
);
await tester.tap(find.text('result.csv'));
await tester.pumpAndSettle();
await tester.tap(_inDialog(_Platform.material, 'Open'));
await tester.pumpAndSettle();
expect(opened, [
Uri.parse('http://127.0.0.1:8081/artifacts/1/1/result.csv'),
]);
expect(find.text('Link opened externally.'), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
});
testWidgets('an unsafe recorded url offers no open or copy action', (
tester,
) async {
await _pumpGallery(tester, _Platform.material, [
step(
stage: 'review',
visit: 1,
artifacts: [_recorded('result.csv', url: '//evil.test/result.csv')],
),
], configuredEndpoint: 'ws://127.0.0.1:8081/connect');
await tester.tap(find.text('result.csv'));
await tester.pumpAndSettle();
expect(
_inDialog(
_Platform.material,
'The recorded artifact URL cannot be opened safely.',
),
findsOneWidget,
);
expect(_inDialog(_Platform.material, 'Open'), findsNothing);
expect(_inDialog(_Platform.material, 'Copy link'), findsNothing);
});
testWidgets('a record with no url is explicit and offers no action', (
tester,
) async {
await _pumpGallery(tester, _Platform.material, [
step(
stage: 'review',
visit: 1,
artifacts: [
<String, dynamic>{
'name': 'result.csv',
'url': '',
'content_type': 'text/csv',
'size_bytes': 10,
},
],
),
]);
await tester.tap(find.text('result.csv'));
await tester.pumpAndSettle();
expect(
_inDialog(_Platform.material, 'No artifact URL recorded.'),
findsOneWidget,
);
expect(_inDialog(_Platform.material, 'Open'), findsNothing);
});
testWidgets('Copy link copies the resolved url, separate from Open', (
tester,
) async {
final copied = <String>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
if (call.method == 'Clipboard.setData') {
copied.add((call.arguments as Map)['text'] as String);
}
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
final opened = <Uri>[];
await _pumpGallery(
tester,
_Platform.material,
[
step(
stage: 'review',
visit: 1,
artifacts: [
_recorded('result.csv', url: '/artifacts/1/1/result.csv'),
],
),
],
configuredEndpoint: 'ws://127.0.0.1:8081/connect',
openExternal: (uri) async {
opened.add(uri);
return true;
},
);
await tester.tap(find.text('result.csv'));
await tester.pumpAndSettle();
await tester.tap(_inDialog(_Platform.material, 'Copy link'));
await tester.pumpAndSettle();
expect(copied, ['http://127.0.0.1:8081/artifacts/1/1/result.csv']);
expect(opened, isEmpty);
expect(find.text('Link copied.'), findsOneWidget);
});
testWidgets('an executing run says capture pending', (tester) async {
await _pumpGallery(tester, _Platform.material, [
step(
stage: 'review',
visit: 1,
includeArtifacts: false,
status: 'running',
),
], executing: true);
expect(find.text('Artifacts · capture pending'), findsOneWidget);
});
}
@@ -0,0 +1,114 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
Map<String, dynamic> run([Map<String, dynamic> overrides = const {}]) => {
'id': 1,
'name': 'Plan and land',
'title': null,
'status': 'failed',
'created_at': '2026-10-19T10:00:00Z',
'finished_at': '2026-10-19T10:05:00Z',
'diagnostic': '',
...overrides,
};
void main() {
group('dismissal and clear-all snapshot', () {
test('a dismissed identity is filtered out and never returns', () {
final rows = [
run({'id': 7, 'status': 'waiting', 'title': 'Wait'}),
];
final dismissed = attentionDismiss(const {}, '7:Decision');
expect(attentionEntries(rows, dismissed: dismissed), isEmpty);
expect(attentionEntries(rows, dismissed: dismissed), isEmpty);
});
test('a different kind for the same run is a different identity', () {
final dismissed = attentionDismiss(const {}, '7:Decision');
final failed = run({'id': 7, 'status': 'failed', 'diagnostic': 'later'});
final entries = attentionEntries([failed], dismissed: dismissed);
expect(entries.single.key, '7:Failed');
expect(entries.single.detail, 'later');
});
test('dismiss ignores a blank key and adds once', () {
final one = attentionDismiss(const {}, '1:Failed');
expect(one, {'1:Failed'});
expect(attentionDismiss(one, '1:Failed'), {'1:Failed'});
expect(attentionDismiss(one, ' '), {'1:Failed'});
expect(one, {'1:Failed'}, reason: 'input set is not mutated');
});
test('clear all applies only the identities in the open snapshot', () {
final a = attentionEntryFor(run({'id': 1}))!;
final snapshot = attentionDismissalSnapshot([a]);
final b = attentionEntryFor(run({'id': 2}))!;
final after = attentionDismissAll(const {}, snapshot);
expect(after, {'1:Failed'});
expect(after.contains(b.key), isFalse);
expect(
attentionEntries([
run({'id': 1}),
run({'id': 2}),
], dismissed: after).map((entry) => entry.runId),
[2],
);
});
test('the snapshot is a defensive copy', () {
final a = attentionEntryFor(run({'id': 1}))!;
final b = attentionEntryFor(run({'id': 2}))!;
final live = [a, b];
final snapshot = attentionDismissalSnapshot(live);
live.add(attentionEntryFor(run({'id': 3}))!);
expect(snapshot.map((entry) => entry.runId), [1, 2]);
expect(snapshot, isNot(same(live)));
});
});
group('persistence', () {
test('the key is the documented one', () {
expect(attentionStorageKey, 'pipelines.next.attention.v1');
expect(attentionStorageKey, isNot('pipelines.web.attention.v1'));
});
test('encoding is one sorted JSON array and round-trips', () {
final encoded = encodeAttentionDismissals({
'9:Failed',
'1:Decision',
'4:Failed',
});
expect(encoded, '["1:Decision","4:Failed","9:Failed"]');
expect(decodeAttentionDismissals(encoded), {
'1:Decision',
'4:Failed',
'9:Failed',
});
expect(encodeAttentionDismissals(const {}), '[]');
});
test('blank or unreadable storage decodes to empty and never throws', () {
for (final stored in [
null,
'',
' ',
'not json',
'{',
'"a string"',
'{}',
'42',
]) {
expect(decodeAttentionDismissals(stored), isEmpty);
}
});
test('a JSON array keeps only non-empty strings', () {
expect(
decodeAttentionDismissals(
'["1:Failed", 2, null, {"a":1}, "3:Decision", ""]',
),
{'1:Failed', '3:Decision'},
);
});
});
}
@@ -0,0 +1,334 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
Map<String, dynamic> run([Map<String, dynamic> overrides = const {}]) => {
'id': 1,
'name': 'Plan and land',
'title': null,
'status': 'failed',
'created_at': '2026-10-19T10:00:00Z',
'finished_at': '2026-10-19T10:05:00Z',
'diagnostic': '',
...overrides,
};
void main() {
group('qualification', () {
test('only waiting and failed qualify; every other status asks nobody', () {
expect(attentionKindOf('waiting'), AttentionKind.decision);
expect(attentionKindOf('failed'), AttentionKind.failed);
for (final status in [
'queued',
'running',
'succeeded',
'canceled',
'cancelled',
'interrupted',
'active',
'blocked',
'skipped',
'unknown',
'',
' ',
null,
'FAILED?',
]) {
expect(
attentionKindOf(status),
isNull,
reason: 'status ${status ?? 'null'} must not qualify',
);
}
});
test('trims and lowercases the server words', () {
expect(attentionKindOf(' Waiting '), AttentionKind.decision);
expect(attentionKindOf('Failed\n'), AttentionKind.failed);
expect(attentionKindOf('WAITING'), AttentionKind.decision);
});
test('ranks are Decision 0 then Failed 1', () {
expect(AttentionKind.decision.rank, 0);
expect(AttentionKind.failed.rank, 1);
});
test('waiting excludes audit/export handoffs, not resource waits', () {
expect(
attentionKindForRun(run({'status': 'waiting'})),
AttentionKind.decision,
);
expect(
attentionKindForRun(
run({'status': 'waiting', 'export_pending_sequence': 4}),
),
isNull,
);
expect(
attentionKindForRun(
run({'status': 'waiting', 'export_pending_sequence': ' 2 '}),
),
isNull,
);
expect(
attentionKindForRun(
run({'status': 'waiting', 'export_pending_sequence': 0}),
),
AttentionKind.decision,
);
// web/src/attention.js and Attention.kt never consult resource_wait; the
// server retired it, so a stale value must not hide a real decision.
for (final stale in [
{'resource': 'device-1'},
'device-1',
true,
1,
]) {
expect(
attentionKindForRun(
run({'status': 'waiting', 'resource_wait': stale}),
),
AttentionKind.decision,
reason: 'resource_wait $stale must not suppress a decision',
);
}
// A failed run stays failed even if a stale export field survived.
expect(
attentionKindForRun(
run({'status': 'failed', 'export_pending_sequence': 4}),
),
AttentionKind.failed,
);
});
test(
'nonqualifying runs are dropped entirely, including malformed ids',
() {
final entries = attentionEntries([
run({'id': 1, 'status': 'succeeded'}),
run({'id': 2, 'status': 'running'}),
run({'id': 3, 'status': 'failed'}),
run({'id': 4, 'status': 'queued'}),
run({'id': 'not-a-number', 'status': 'failed'}),
run({'id': 0, 'status': 'failed'}),
]);
expect(entries.map((entry) => entry.runId), [3]);
expect(attentionEntries(null), isEmpty);
},
);
});
group('identity and wording', () {
test('identity is exactly {runId}:{kind}', () {
expect(attentionKey(440, AttentionKind.failed), '440:Failed');
expect(attentionKey(12, AttentionKind.decision), '12:Decision');
});
test('label is the trimmed title else the pipeline name', () {
expect(attentionEntryFor(run({'title': ' My run '}))!.label, 'My run');
expect(attentionEntryFor(run({'title': ' '}))!.label, 'Plan and land');
expect(attentionEntryFor(run({'title': null}))!.label, 'Plan and land');
});
test(
'detail is the decision line or the trimmed diagnostic else Run failed',
() {
expect(
attentionDetail(AttentionKind.decision, run({'status': 'waiting'})),
'Waiting for your decision',
);
expect(
attentionDetail(
AttentionKind.failed,
run({'diagnostic': ' boom '}),
),
'boom',
);
expect(
attentionDetail(AttentionKind.failed, run({'diagnostic': ' '})),
'Run failed',
);
expect(
attentionDetail(AttentionKind.failed, run({'diagnostic': null})),
'Run failed',
);
},
);
test('row description is exactly {pipeline} · {detail}', () {
final entry = attentionEntryFor(
run({'title': 'T', 'diagnostic': 'failed hard'}),
)!;
expect(attentionRowDescription(entry), 'Plan and land · failed hard');
});
test('badge label is bare Notifications when empty, else the count', () {
expect(attentionBadgeLabel(0), 'Notifications');
expect(attentionBadgeLabel(-3), 'Notifications');
expect(attentionBadgeLabel(1), 'Notifications, 1 needing attention');
expect(attentionBadgeLabel(171), 'Notifications, 171 needing attention');
});
test('the entry keeps the whole summary, including unknown fields', () {
final source = run({
'unknown_future_field': {'keep': true},
'id': 7,
});
final entry = attentionEntryFor(source)!;
expect(entry.run['unknown_future_field'], {'keep': true});
expect(entry.run, same(source));
});
});
group('ordering', () {
test('kind rank, then recency descending, then run id descending', () {
final entries = attentionEntries([
run({
'id': 10,
'status': 'failed',
'finished_at': '2026-10-19T10:00:00Z',
}),
run({
'id': 11,
'status': 'waiting',
'finished_at': '2026-10-19T09:00:00Z',
}),
run({
'id': 12,
'status': 'failed',
'finished_at': '2026-10-19T11:00:00Z',
}),
run({
'id': 13,
'status': 'waiting',
'finished_at': '2026-10-19T08:00:00Z',
}),
]);
expect(entries.map((entry) => entry.runId), [11, 13, 12, 10]);
});
test('recency falls back to created_at when finished_at is blank', () {
final entries = attentionEntries([
run({
'id': 1,
'status': 'failed',
'finished_at': '',
'created_at': '2026-10-19T12:00:00Z',
}),
run({
'id': 2,
'status': 'failed',
'finished_at': '2026-10-19T11:00:00Z',
}),
]);
expect(entries.map((entry) => entry.runId), [1, 2]);
});
test('equal kind and recency tie by run id descending and stay stable', () {
final rows = [
run({'id': 3, 'finished_at': '2026-10-19T10:00:00Z'}),
run({'id': 9, 'finished_at': '2026-10-19T10:00:00Z'}),
run({'id': 5, 'finished_at': '2026-10-19T10:00:00Z'}),
];
expect(attentionEntries(rows).map((entry) => entry.runId), [9, 5, 3]);
expect(attentionEntries(rows.reversed).map((entry) => entry.runId), [
9,
5,
3,
]);
});
});
group('local-day window', () {
final since = DateTime.utc(2026, 10, 20);
final rows = [
run({'id': 1, 'finished_at': '2026-10-19T21:33:27Z'}),
run({'id': 2, 'finished_at': '2026-10-20T10:00:00Z'}),
];
test('startOfLocalDay is local midnight, injectable for tests', () {
final now = DateTime(2026, 10, 20, 15, 4, 5, 6);
final start = startOfLocalDay(now: now);
expect(start, DateTime(2026, 10, 20));
expect(start.hour, 0);
expect(start.minute, 0);
expect(start.second, 0);
expect(start.millisecond, 0);
expect(start.isBefore(now), isTrue);
expect(start.toLocal(), start);
});
test('a cutoff drops older work and keeps newer work', () {
expect(attentionEntries(rows, since: since).map((entry) => entry.runId), [
2,
]);
});
test('no cutoff, and an epoch-zero cutoff, show everything', () {
expect(attentionEntries(rows).map((entry) => entry.runId), [2, 1]);
expect(
attentionEntries(
rows,
since: DateTime.fromMillisecondsSinceEpoch(0),
).map((entry) => entry.runId),
[2, 1],
);
});
test('the cutoff applies to waiting decisions as well as failures', () {
expect(
attentionEntries([
run({
'id': 3,
'status': 'waiting',
'finished_at': '2026-10-19T09:00:00Z',
}),
], since: since),
isEmpty,
);
});
test('unparseable or blank recency is kept, as in the browser', () {
for (final recency in ['', ' ', 'not a timestamp']) {
final kept = attentionEntries([
run({'id': 4, 'finished_at': recency, 'created_at': recency}),
], since: since);
expect(
kept.map((entry) => entry.runId),
[4],
reason: 'recency ${recency.isEmpty ? '<blank>' : recency} is kept',
);
}
});
test('finished_at is the recency the cutoff reads, else created_at', () {
expect(
attentionEntries([
run({
'id': 5,
'created_at': '2026-10-18T09:00:00Z',
'finished_at': '2026-10-20T09:00:00Z',
}),
], since: since).map((entry) => entry.runId),
[5],
);
expect(
attentionEntries([
run({
'id': 6,
'created_at': '2026-10-18T09:00:00Z',
'finished_at': '',
}),
], since: since),
isEmpty,
);
});
test('dismissal and the cutoff compose', () {
final dismissed = attentionDismiss(const {}, '2:Failed');
expect(
attentionEntries(rows, dismissed: dismissed, since: since),
isEmpty,
);
});
});
}
@@ -0,0 +1,224 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
import 'package:pipelines_app/features/attention/domain/attention_transitions.dart';
Map<String, dynamic> run([Map<String, dynamic> overrides = const {}]) => {
'id': 1,
'name': 'Plan and land',
'title': null,
'status': 'failed',
'created_at': '2026-10-19T10:00:00Z',
'finished_at': '2026-10-19T10:05:00Z',
'diagnostic': '',
...overrides,
};
void main() {
test('a seeded failed/waiting run raises nothing', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 1, 'status': 'failed'}),
run({'id': 2, 'status': 'waiting'}),
]);
expect(detector.observe(run({'id': 1, 'status': 'failed'})), isNull);
expect(detector.observe(run({'id': 2, 'status': 'waiting'})), isNull);
expect(detector.emittedKeys, isEmpty);
});
test('a first-seen run raises nothing and becomes the baseline', () {
final detector = AttentionTransitionDetector();
expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull);
expect(detector.statusOf(5), 'failed');
expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull);
expect(detector.emittedKeys, isEmpty);
});
test('entering failed from a known running run emits exactly once', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 5, 'status': 'running'}),
]);
final first = detector.observe(run({'id': 5, 'status': 'failed'}));
expect(first, isNotNull);
expect(first!.runId, 5);
expect(first.kind, AttentionKind.failed);
expect(first.key, '5:Failed');
expect(first.entry.label, 'Plan and land');
expect(first.entry.detail, 'Run failed');
expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull);
expect(detector.emittedKeys, {'5:Failed'});
});
test('entering a human waiting state emits a Decision', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 6, 'status': 'running'}),
]);
final transition = detector.observe(
run({'id': 6, 'status': 'waiting', 'title': ' Decide '}),
);
expect(transition, isNotNull);
expect(transition!.kind, AttentionKind.decision);
expect(transition.key, '6:Decision');
expect(transition.entry.label, 'Decide');
expect(transition.entry.detail, 'Waiting for your decision');
});
test('waiting to failed is a new kind and emits once', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 7, 'status': 'waiting'}),
]);
final transition = detector.observe(run({'id': 7, 'status': 'failed'}));
expect(transition!.key, '7:Failed');
expect(detector.emittedKeys, {'7:Failed'});
});
test('a run that leaves the state and returns may emit again', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 8, 'status': 'running'}),
]);
expect(detector.observe(run({'id': 8, 'status': 'failed'})), isNotNull);
expect(detector.observe(run({'id': 8, 'status': 'running'})), isNull);
expect(detector.emittedKeys, isEmpty);
final again = detector.observe(run({'id': 8, 'status': 'failed'}));
expect(again, isNotNull);
expect(detector.observe(run({'id': 8, 'status': 'failed'})), isNull);
});
test('nonqualifying statuses never emit', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 9, 'status': 'queued'}),
]);
for (final status in [
'running',
'succeeded',
'canceled',
'interrupted',
'unknown',
]) {
expect(
detector.observe(run({'id': 9, 'status': status})),
isNull,
reason: 'status $status must not emit',
);
}
expect(detector.emittedKeys, isEmpty);
});
test(
'an export wait never emits a Decision even though status is waiting',
() {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 10, 'status': 'running'}),
]);
expect(
detector.observe(
run({'id': 10, 'status': 'waiting', 'export_pending_sequence': 2}),
),
isNull,
);
expect(detector.emittedKeys, isEmpty);
},
);
test('dismissed identities are marked seen but do not emit', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 11, 'status': 'running'}),
]);
expect(
detector.observe(
run({'id': 11, 'status': 'failed'}),
dismissed: {'11:Failed'},
),
isNull,
);
expect(detector.emittedKeys, {'11:Failed'});
expect(detector.observe(run({'id': 11, 'status': 'failed'})), isNull);
});
test('a reconnect reseed produces no transition and no replay', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 12, 'status': 'failed'}),
]);
detector.resetForReconnect();
detector.reseed([
run({'id': 12, 'status': 'failed'}),
]);
expect(detector.observe(run({'id': 12, 'status': 'failed'})), isNull);
expect(detector.emittedKeys, isEmpty);
});
test('a reseed keeps still-qualifying keys and prunes the rest', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 20, 'status': 'running'}),
run({'id': 21, 'status': 'running'}),
]);
expect(detector.observe(run({'id': 20, 'status': 'failed'})), isNotNull);
expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNotNull);
expect(detector.emittedKeys, {'20:Failed', '21:Decision'});
detector.reseed([
run({'id': 20, 'status': 'failed'}),
run({'id': 21, 'status': 'succeeded'}),
]);
// 20 still qualifies, so its key survives; 21 no longer asks, so its key is
// pruned and a genuine later transition can be raised once more.
expect(detector.emittedKeys, {'20:Failed'});
expect(detector.observe(run({'id': 20, 'status': 'failed'})), isNull);
expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNotNull);
expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNull);
});
test('a reseed keeps the key of a run absent from the read', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 22, 'status': 'running'}),
]);
expect(detector.observe(run({'id': 22, 'status': 'failed'})), isNotNull);
detector.reseed([
run({'id': 23, 'status': 'running'}),
]);
expect(detector.emittedKeys, {'22:Failed'});
// Absence says nothing, so seeing the same state again is not a transition.
expect(detector.observe(run({'id': 22, 'status': 'failed'})), isNull);
});
test('a snapshot bracketed as a seed does not emit or replay', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 13, 'status': 'running'}),
])
..beginSeed();
expect(detector.observe(run({'id': 13, 'status': 'waiting'})), isNull);
detector.endSeed();
expect(detector.observe(run({'id': 13, 'status': 'waiting'})), isNull);
expect(detector.emittedKeys, isEmpty);
});
test('the transition keeps the whole frame, including unknown fields', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 14, 'status': 'running'}),
]);
final frame = run({
'id': 14,
'run_id': 14,
'status': 'failed',
'diagnostic': ' boom ',
'unknown_future_field': ['keep'],
});
final transition = detector.observe(frame);
expect(transition!.entry.detail, 'boom');
expect(transition.run, same(frame));
expect(transition.run['unknown_future_field'], ['keep']);
});
}
@@ -0,0 +1,159 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/graph/domain/stage_definition.dart';
import 'graph_fixtures.dart';
JsonMap _stage() => <String, dynamic>{
'key': 'build',
'prompt': 'Implement the planned change.',
'output': 'A committed change.',
'edges': <String, String?>{
'success': 'audit',
'approved': '#',
'error': '#failure',
},
'fallback_error': true,
'configs': <String, dynamic>{
'provider': 'openai',
'model': 'gpt-5',
'budget_usd': 12.5,
'retries': 2,
'harness': 'codex',
'timeout': '15m',
'skipped_blank': ' ',
'skipped_null': null,
},
'blocks': <String, dynamic>{'tools': 'shell\nread_file'},
'limits': <String, dynamic>{
'max_visits': 3,
'on': <String>['success', 'error'],
},
'memory': <String, dynamic>{'context': 'latest', 'notes': 'keep'},
'notify': <String, dynamic>{
'on': <String>['failure'],
'destination': 'ops@example.test',
'artifacts': <String>['run.log'],
},
'custom_flag': true,
};
void main() {
group('stage fields', () {
test('follow the web pane order, labels and blank-field rules', () {
final fields = stageDefinitionFields(_stage());
expect(fields.map((field) => field.label), <String>[
'Type',
'Prompt',
'Output',
'Outcomes',
'Budget (USD)',
'Harness',
'Model',
'Provider',
'Retries',
'Timeout',
'Tools',
'Max visits',
'Limit on',
'Memory',
'Notify on',
'Notify destination',
'Notify artifacts',
]);
expect(fields.first.value, 'model');
expect(fields[1].block, isTrue);
expect(fields[2].value, 'A committed change.');
expect(
fields[3].value,
'success → audit\n'
'approved → SUCCESS (terminal)\n'
'error → FAILURE (terminal)',
);
expect(fields[4].value, '12.5');
expect(fields[5].value, 'codex');
expect(fields[10].value, 'shell\nread_file');
expect(fields[11].value, '3');
expect(fields[12].value, 'success, error');
expect(fields[13].value, 'context: latest\nnotes: keep');
expect(fields[14].value, 'failure');
expect(fields[15].value, 'ops@example.test');
expect(fields[16].value, 'run.log');
});
test('a blank or absent type reads model; an authored type is kept', () {
expect(effectiveStageType(null), 'model');
expect(effectiveStageType(' '), 'model');
expect(effectiveStageType('shell'), 'shell');
expect(
stageDefinitionFields(<String, dynamic>{'key': 'a'}).single.value,
'model',
);
});
test('config keys outside the known labels are shown verbatim', () {
final fields = stageDefinitionFields(<String, dynamic>{
'key': 'a',
'configs': <String, dynamic>{'temperature': 0},
});
expect(fields.map((field) => field.label), contains('temperature'));
expect(
fields.firstWhere((field) => field.label == 'temperature').value,
'0',
);
});
test('zero visits and missing limits emit no invented rows', () {
final fields = stageDefinitionFields(<String, dynamic>{
'key': 'a',
'limits': <String, dynamic>{'max_visits': 0, 'on': <String>[]},
});
expect(fields.map((field) => field.label), <String>['Type']);
});
test(
'the stage lookup preserves unknown keys and the last declaration',
() {
final graph = <String, dynamic>{
'stages': <dynamic>[
<String, dynamic>{'key': 'build', 'type': 'old'},
_stage(),
],
};
final stage = stageDefinitionFor(graph, 'build');
expect(stage?['type'], isNull);
expect(effectiveStageType(stage?['type']), 'model');
expect(stage?['custom_flag'], isTrue);
expect(stageDefinitionFor(graph, 'ghost'), isNull);
},
);
});
group('terminal fields', () {
test('list incoming definition routes, including the fallback marker', () {
expect(terminalDefinitionFields(linearGraph(), '#failure'), hasLength(1));
final fields = terminalDefinitionFields(linearGraph(), '#failure');
expect(
fields.single.value,
'plan · error* → FAILURE\nship · error → FAILURE',
);
expect(fields.single.block, isTrue);
expect(
terminalDefinitionFields(linearGraph(), '#success').single.value,
'ship · success → SUCCESS',
);
});
test('a terminal with no routes has no fields to invent', () {
expect(
terminalDefinitionFields(<String, dynamic>{}, '#success'),
isEmpty,
);
});
});
}
@@ -0,0 +1,286 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/graph/domain/stage_definition.dart';
import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart';
JsonMap _graph() => <String, dynamic>{
'stages': <dynamic>[
<String, dynamic>{
'key': 'plan',
'type': 'model',
'prompt': 'Plan the change.',
'edges': <String, String?>{'success': 'build', 'error': '#'},
'fallback_error': true,
'configs': <String, dynamic>{'provider': 'openai', 'model': 'gpt-5'},
'limits': <String, dynamic>{
'max_visits': 2,
'on': <String>['error'],
},
'future_field': <String, dynamic>{'kept': true},
},
<String, dynamic>{
'key': 'build',
'type': 'shell',
'edges': <String, String?>{'success': '#success', 'error': '#failure'},
},
],
};
Widget _material(Widget child) => MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('plan definition')),
body: child,
),
);
Widget _cupertino(Widget child, {bool dark = false}) => CupertinoApp(
theme: CupertinoThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
),
home: CupertinoPageScaffold(child: child),
);
StageDefinitionView _view({String key = 'plan'}) => StageDefinitionView(
graph: _graph(),
stageKey: key,
pipelineId: 41,
pipelineName: 'Demo pipeline',
version: 7,
);
/// Finds visible text, including SelectableText's editable body.
Finder _text(String value) => find.byWidgetPredicate(
(widget) =>
(widget is Text && widget.data == value) ||
(widget is SelectableText && widget.data == value),
);
void main() {
testWidgets('a declared stage shows pinned identity and web field values', (
tester,
) async {
await tester.pumpWidget(_material(_view()));
expect(_text('Demo pipeline · v7'), findsOneWidget);
expect(_text('model'), findsOneWidget);
expect(_text('Plan the change.'), findsOneWidget);
expect(
_text('success → build\nerror → FAILURE (terminal)'),
findsOneWidget,
);
expect(_text('Provider'), findsOneWidget);
expect(_text('openai'), findsOneWidget);
expect(_text('Model'), findsOneWidget);
expect(_text('gpt-5'), findsOneWidget);
expect(_text('Max visits'), findsOneWidget);
expect(_text('2'), findsOneWidget);
expect(_text('Limit on'), findsOneWidget);
expect(_text('error'), findsOneWidget);
});
testWidgets('the raw section keeps unknown fields exact and selectable', (
tester,
) async {
await tester.pumpWidget(_material(_view()));
expect(_text(rawStageDefinitionTitle), findsOneWidget);
final raw = tester
.widgetList<SelectableText>(find.byType(SelectableText))
.map((widget) => widget.data ?? '')
.join('\n');
expect(raw, contains('"future_field": {'));
expect(raw, contains('"kept": true'));
expect(raw, contains('"fallback_error": true'));
expect(tester.takeException(), isNull);
});
testWidgets('unknown stages get an explicit missing state, never defaults', (
tester,
) async {
await tester.pumpWidget(_material(_view(key: 'ghost')));
expect(_text(unknownStageDefinition), findsOneWidget);
expect(_text('model'), findsNothing);
expect(_text(rawStageDefinitionTitle), findsNothing);
expect(find.byType(SelectableText), findsNothing);
});
testWidgets('terminals explain definition targets and incoming routes', (
tester,
) async {
await tester.pumpWidget(_material(_view(key: '#failure')));
expect(_text(terminalDefinitionNote), findsOneWidget);
expect(_text('Incoming routes'), findsOneWidget);
expect(
_text('plan · error* → FAILURE\nbuild · error → FAILURE'),
findsOneWidget,
);
expect(_text(rawStageDefinitionTitle), findsNothing);
expect(_text('successful'), findsNothing);
});
testWidgets('Cupertino uses its theme roles in dark mode', (tester) async {
late Color secondary;
await tester.pumpWidget(
_cupertino(
Builder(
builder: (context) {
secondary = CupertinoColors.secondaryLabel.resolveFrom(context);
return _view();
},
),
dark: true,
),
);
final identity = tester.widget<Text>(_text('Demo pipeline · v7'));
expect(identity.style?.color, secondary);
expect(_text('Plan the change.'), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('the Material helper opens one bar and Back closes it', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () => openStageDefinition(
context,
graph: _graph(),
stageKey: 'plan',
pipelineId: 41,
pipelineName: 'Demo pipeline',
version: 7,
),
child: const Text('Open definition'),
),
),
),
),
);
await tester.tap(find.text('Open definition'));
await tester.pumpAndSettle();
expect(_text('plan definition'), findsOneWidget);
expect(find.byType(AppBar), findsOneWidget);
expect(find.byType(BackButton), findsOneWidget);
final route = ModalRoute.of(
tester.element(find.byType(StageDefinitionView)),
);
expect(route?.settings.name, 'stage-definition/41/7/plan');
await tester.pageBack();
await tester.pumpAndSettle();
expect(_text('Open definition'), findsOneWidget);
expect(find.byType(StageDefinitionView), findsNothing);
});
testWidgets('the Cupertino helper opens one native bar and Back closes it', (
tester,
) async {
await tester.pumpWidget(
CupertinoApp(
home: Builder(
builder: (context) => CupertinoPageScaffold(
child: CupertinoButton(
onPressed: () => openStageDefinition(
context,
graph: _graph(),
stageKey: '#success',
pipelineId: 41,
pipelineName: 'Demo pipeline',
version: 7,
),
child: const Text('Open terminal'),
),
),
),
),
);
await tester.tap(find.text('Open terminal'));
await tester.pumpAndSettle();
expect(_text('Success definition'), findsOneWidget);
expect(_text('#success definition'), findsNothing);
expect(find.byType(CupertinoNavigationBar), findsOneWidget);
expect(find.byType(CupertinoNavigationBarBackButton), findsOneWidget);
expect(_text('Incoming routes'), findsOneWidget);
await tester.tap(find.byType(CupertinoNavigationBarBackButton));
await tester.pumpAndSettle();
expect(_text('Open terminal'), findsOneWidget);
expect(find.byType(StageDefinitionView), findsNothing);
});
testWidgets('the Material helper titles a terminal with its display label', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () => openStageDefinition(
context,
graph: _graph(),
stageKey: '#failure',
pipelineId: 41,
pipelineName: 'Demo pipeline',
version: 7,
),
child: const Text('Open failure'),
),
),
),
),
);
await tester.tap(find.text('Open failure'));
await tester.pumpAndSettle();
expect(_text('Failure definition'), findsOneWidget);
expect(_text('#failure definition'), findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('selectable blocks force the host strut for one line rhythm', (
tester,
) async {
await tester.pumpWidget(_cupertino(_view()));
final selectable = tester
.widgetList<SelectableText>(find.byType(SelectableText))
.toList();
expect(selectable.length, greaterThanOrEqualTo(2));
for (final widget in selectable) {
final strut = widget.strutStyle;
expect(strut, isNotNull);
// The host's own metrics, forced: a fallback glyph cannot widen a block.
expect(strut!.forceStrutHeight, isTrue);
expect(strut.fontFamily, widget.style?.fontFamily);
expect(strut.fontSize, widget.style?.fontSize);
}
final outcomes = selectable.firstWhere(
(widget) => (widget.data ?? '').contains('success → build'),
);
final raw = selectable.firstWhere(
(widget) => (widget.data ?? '').startsWith('{'),
);
expect(outcomes.strutStyle, raw.strutStyle);
});
test('field labels are the web words', () {
expect(stageConfigLabel('budget_usd'), 'Budget (USD)');
expect(stageConfigLabel('budget_tokens'), 'Budget (tokens)');
expect(stageConfigLabel('custom'), 'custom');
});
}
@@ -0,0 +1,161 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_action.dart';
import 'package:pipelines_app/features/runs/data/runs_repository.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_view.dart';
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
import '../../artifacts/domain/artifact_fixtures.dart';
enum _Platform { material, cupertino }
class _FakeGateway implements ApiGateway {
_FakeGateway(this.detail);
final JsonMap detail;
@override
Stream<JsonMap> get frames => const Stream<JsonMap>.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type != 'get_run') throw UnsupportedError(type);
return Future.value({'run_detail': detail});
}
}
JsonMap _run({required List<JsonMap> steps}) => <String, dynamic>{
'id': 21,
'title': 'Artifacts wiring run',
'name': 'gallery',
'status': 'succeeded',
'steps': steps,
};
Future<void> _pumpDetail(
WidgetTester tester,
_Platform platform,
RunsController controller,
ApiGateway gateway,
) async {
tester.view.physicalSize = const Size(500, 1200);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final view = RunDetailView(
controller: controller,
gateway: gateway,
onBack: () {},
);
await tester.pumpWidget(
platform == _Platform.material
? MaterialApp(home: Scaffold(body: view))
: CupertinoApp(
builder: (context, app) => Theme(
data: ThemeData(platform: TargetPlatform.iOS),
child: app!,
),
home: CupertinoPageScaffold(child: view),
),
);
await tester.pumpAndSettle();
}
Future<RunsController> _loaded(ApiGateway gateway) async {
final controller = RunsController(RunsRepository(gateway));
await controller.select(21);
return controller;
}
void main() {
for (final platform in _Platform.values) {
testWidgets('${platform.name}: the action opens the recorded groups', (
tester,
) async {
final gateway = _FakeGateway(
_run(
steps: [
step(
stage: 'implementer',
sequence: 1,
artifacts: [
artifact(
'build.log',
contentType: 'text/plain',
sizeBytes: 2337,
),
],
),
step(
stage: 'reviewer',
sequence: 2,
artifacts: [
artifact(
'shot.png',
contentType: 'image/png',
sizeBytes: 80544,
),
],
),
],
),
);
final controller = await _loaded(gateway);
addTearDown(controller.dispose);
await _pumpDetail(tester, platform, controller, gateway);
expect(find.byKey(runArtifactsButtonKey), findsOneWidget);
await tester.tap(find.byKey(runArtifactsButtonKey));
await tester.pumpAndSettle();
expect(find.text('Artifacts · 2 recorded'), findsOneWidget);
expect(find.text('build.log'), findsOneWidget);
expect(find.text('shot.png'), findsOneWidget);
expect(find.text('implementer · visit 1'), findsOneWidget);
expect(find.text('reviewer · visit 1'), findsOneWidget);
});
}
testWidgets('the action is offered only when the detail has steps', (
tester,
) async {
final gateway = _FakeGateway(_run(steps: const []));
final controller = await _loaded(gateway);
addTearDown(controller.dispose);
await _pumpDetail(tester, _Platform.material, controller, gateway);
expect(find.byKey(runArtifactsButtonKey), findsNothing);
});
testWidgets('a recorded empty capture keeps its explicit wording', (
tester,
) async {
final gateway = _FakeGateway(
_run(
steps: [step(stage: 'reviewer', visit: 1, artifacts: const [])],
),
);
final controller = await _loaded(gateway);
addTearDown(controller.dispose);
await _pumpDetail(tester, _Platform.material, controller, gateway);
await tester.tap(find.byKey(runArtifactsButtonKey));
await tester.pumpAndSettle();
expect(find.text('No artifacts recorded for this run.'), findsOneWidget);
});
testWidgets('an unavailable capture is never reported as empty', (
tester,
) async {
final gateway = _FakeGateway(
_run(steps: [step(stage: 'reviewer', visit: 1, includeArtifacts: false)]),
);
final controller = await _loaded(gateway);
addTearDown(controller.dispose);
await _pumpDetail(tester, _Platform.material, controller, gateway);
await tester.tap(find.byKey(runArtifactsButtonKey));
await tester.pumpAndSettle();
expect(find.text('Artifacts · capture unavailable'), findsOneWidget);
expect(find.text('No artifacts recorded for this run.'), findsNothing);
});
}
@@ -0,0 +1,162 @@
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/ui/editor/schedule_editor_selectors.dart';
import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_wording.dart';
import 'schedule_editor_harness.dart';
void main() {
testWidgets('invalid draft shows field errors and sends nothing', (
tester,
) async {
final calls = <JsonMap>[];
await pumpScheduleEditor(
tester,
draft: createDraft(),
onSubmit: (record) async => calls.add(record),
);
expect(find.text('Add schedule'), findsOneWidget);
await tester.tap(find.byKey(scheduleEditorSubmitKey));
await tester.pump();
expect(find.text('Enter a schedule name.'), findsOneWidget);
expect(find.text('Enter a prompt.'), findsOneWidget);
expect(calls, isEmpty);
expect(
tester
.widget<TextField>(find.byKey(scheduleEditorVersionKey))
.controller!
.text,
'2',
);
});
testWidgets('valid create sends the exact save record', (tester) async {
final calls = <JsonMap>[];
final draft = createDraft();
await pumpScheduleEditor(
tester,
draft: draft,
onSubmit: (record) async => calls.add(record),
);
await enterField(tester, scheduleEditorNameKey, 'Probe schedule');
await enterField(
tester,
scheduleEditorPromptKey,
'Summarise the release notes.',
);
await tester.tap(find.byKey(scheduleEditorDayKey('mon')));
await tester.tap(find.byKey(scheduleEditorDayKey('wed')));
await tester.pump();
await tester.tap(find.byKey(scheduleEditorSubmitKey));
await tester.pumpAndSettle();
expect(calls, hasLength(1));
expect(calls.single, {
'id': 0,
'name': 'Probe schedule',
'pipeline_id': 4,
'version': 2,
'enabled': true,
'input': {'prompt': 'Summarise the release notes.'},
'workspace': '/srv/research',
'rule': {
'every': '24h',
'days': ['mon', 'wed'],
'timezone': 'Europe/London',
},
'notify_mode': 'auto',
});
expect(calls.single.containsKey('revision'), isFalse);
expect(draft.source, isNull);
});
testWidgets('clock times, paused state and notifications reach the record', (
tester,
) async {
final calls = <JsonMap>[];
await pumpScheduleEditor(
tester,
draft: createDraft(name: 'Clock schedule', prompt: 'Run at times'),
onSubmit: (record) async => calls.add(record),
);
await tester.tap(find.byKey(scheduleEditorTimerKey));
await tester.pumpAndSettle();
await tester.tap(find.text('Clock times').last);
await tester.pumpAndSettle();
expect(find.text('Clock times (24h, comma separated)'), findsOneWidget);
expect(find.text('Interval (at least 1m)'), findsNothing);
await enterField(tester, scheduleEditorTimesKey, '09:00, 17:30');
await tester.tap(find.byKey(scheduleEditorEnabledKey));
await tester.tap(find.byKey(scheduleEditorNotifyKey));
await tester.pumpAndSettle();
await tester.tap(find.text('off').last);
await tester.pumpAndSettle();
await tester.tap(find.byKey(scheduleEditorSubmitKey));
await tester.pumpAndSettle();
expect(calls.single['enabled'], isFalse);
expect(calls.single['notify_mode'], 'off');
expect(calls.single['rule'], {
'times': ['09:00', '17:30'],
'timezone': 'Europe/London',
});
});
testWidgets('editing keeps CAS identity and unknown raw fields', (
tester,
) async {
final calls = <JsonMap>[];
await pumpScheduleEditor(
tester,
draft: editDraft(),
onSubmit: (record) async => calls.add(record),
);
expect(find.text('Edit schedule'), findsOneWidget);
expect(
tester
.widget<TextField>(find.byKey(scheduleEditorNameKey))
.controller!
.text,
'Saved topic',
);
await enterField(tester, scheduleEditorNameKey, 'Edited topic');
await tester.tap(find.byKey(scheduleEditorSubmitKey));
await tester.pumpAndSettle();
final record = calls.single;
expect(record['id'], 9);
expect(record['revision'], 13);
expect(record['pipeline_id'], 4);
expect(record['name'], 'Edited topic');
expect(record['input'], {
'prompt': 'Topic',
'count': 4,
'flag': false,
'nested': {
'list': [null, 2],
},
});
expect(record['rule'], {
'times': ['09:00', '17:30'],
'days': ['fri', 'mon'],
'future': 'keep',
});
expect(record['model'], 'provider/model');
expect(record['stage_models'], {'research': 'provider/other'});
expect(record['write_paths'], ['src/file.go']);
expect(record['allow_tools'], isTrue);
expect(record['title'], 'Saved title');
expect(record['output_format'], 'json');
expect(record['notify_mode'], 'off');
expect(record['server_extra'], {
'keep': [1, true],
});
});
}
@@ -0,0 +1,82 @@
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/schedules/domain/editor/schedule_draft.dart';
import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart';
import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_form.dart';
import '../../domain/editor/draft_fixtures.dart';
ScheduleDraft createDraft({
String name = '',
String prompt = '',
String version = '2',
String workspace = '/srv/research',
String timezone = 'Europe/London',
}) =>
ScheduleDraft.create(
pipelineId: 4,
version: version,
workspace: workspace,
timezone: timezone,
)
..name = name
..prompt = prompt;
ScheduleDraft editDraft() =>
ScheduleDraft.fromSchedule(SavedSchedule(deepCopy(completeRecord())));
Future<void> pumpScheduleEditor(
WidgetTester tester, {
required ScheduleDraft draft,
required Future<void> Function(JsonMap record) onSubmit,
bool cupertino = false,
bool dark = false,
double width = 390,
double height = 1600,
double textScale = 1,
VoidCallback? onCancel,
}) async {
tester.view.physicalSize = Size(width, height);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final form = SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: ScheduleEditorForm(
draft: draft,
onSubmit: onSubmit,
onCancel: onCancel,
),
);
Widget scaled(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: app!,
);
await tester.pumpWidget(
cupertino
? CupertinoApp(
theme: CupertinoThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
),
builder: scaled,
home: CupertinoPageScaffold(child: SafeArea(child: form)),
)
: MaterialApp(
theme: ThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
),
builder: scaled,
home: Scaffold(body: SafeArea(child: form)),
),
);
await tester.pumpAndSettle();
}
Future<void> enterField(WidgetTester tester, Key key, String value) async {
await tester.enterText(find.byKey(key), value);
await tester.pump();
}
@@ -0,0 +1,164 @@
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/schedules/ui/editor/schedule_editor_selectors.dart';
import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_wording.dart';
import 'schedule_editor_harness.dart';
void main() {
testWidgets('async refusal keeps typed values and a retry can succeed', (
tester,
) async {
final calls = <JsonMap>[];
Object? refusal = StateError('revision 13 is stale');
await pumpScheduleEditor(
tester,
draft: createDraft(name: 'Probe schedule', prompt: 'Keep these words'),
onSubmit: (record) async {
calls.add(record);
if (refusal case final error?) throw error;
},
);
await tester.tap(find.byKey(scheduleEditorSubmitKey));
await tester.pumpAndSettle();
expect(find.byKey(scheduleEditorErrorKey), findsOneWidget);
expect(find.textContaining('revision 13 is stale'), findsOneWidget);
expect(find.textContaining('Your draft is preserved.'), findsOneWidget);
expect(
tester
.widget<TextField>(find.byKey(scheduleEditorNameKey))
.controller!
.text,
'Probe schedule',
);
expect(
tester
.widget<TextField>(find.byKey(scheduleEditorPromptKey))
.controller!
.text,
'Keep these words',
);
expect(
tester
.widget<FilledButton>(find.byKey(scheduleEditorSubmitKey))
.onPressed,
isNotNull,
);
refusal = null;
await tester.tap(find.byKey(scheduleEditorSubmitKey));
await tester.pumpAndSettle();
expect(calls, hasLength(2));
expect(calls.last['name'], 'Probe schedule');
expect(find.byKey(scheduleEditorErrorKey), findsNothing);
});
testWidgets('a sending form locks controls and rejects a second submit', (
tester,
) async {
final gate = Completer<void>();
var calls = 0;
await pumpScheduleEditor(
tester,
draft: createDraft(name: 'Probe schedule', prompt: 'Run once'),
onSubmit: (_) {
calls++;
return gate.future;
},
);
await tester.tap(find.byKey(scheduleEditorSubmitKey));
await tester.pump();
expect(find.text('Saving…'), findsOneWidget);
expect(
tester
.widget<FilledButton>(find.byKey(scheduleEditorSubmitKey))
.onPressed,
isNull,
);
expect(
tester.widget<TextField>(find.byKey(scheduleEditorNameKey)).enabled,
isFalse,
);
await tester.tap(find.byKey(scheduleEditorSubmitKey));
await tester.pump();
expect(calls, 1);
gate.complete();
await tester.pumpAndSettle();
expect(find.text('Save schedule'), findsOneWidget);
expect(
tester
.widget<FilledButton>(find.byKey(scheduleEditorSubmitKey))
.onPressed,
isNotNull,
);
});
testWidgets('Cupertino form uses native fields and action sheets', (
tester,
) async {
final calls = <JsonMap>[];
await pumpScheduleEditor(
tester,
cupertino: true,
draft: createDraft(name: 'Cupertino schedule', prompt: 'Native fields'),
onSubmit: (record) async => calls.add(record),
);
expect(find.byType(CupertinoTextField), findsNWidgets(6));
expect(find.byType(TextField), findsNothing);
expect(find.byType(CupertinoSwitch), findsOneWidget);
expect(find.byType(Switch), findsNothing);
expect(find.byType(CupertinoCheckbox), findsNWidgets(7));
expect(find.byType(Checkbox), findsNothing);
await tester.tap(find.byKey(scheduleEditorTimerKey));
await tester.pumpAndSettle();
await tester.tap(find.text('Clock times').last);
await tester.pumpAndSettle();
await enterField(tester, scheduleEditorTimesKey, '06:30');
await tester.tap(find.byKey(scheduleEditorDayKey('mon')));
await tester.pump();
expect(
tester
.widget<CupertinoCheckbox>(find.byKey(scheduleEditorDayKey('mon')))
.value,
isTrue,
);
await tester.tap(find.byKey(scheduleEditorEnabledKey));
await tester.pump();
await tester.tap(find.byKey(scheduleEditorSubmitKey));
await tester.pumpAndSettle();
expect(calls.single['enabled'], isFalse);
expect(calls.single['rule'], {
'times': ['06:30'],
'days': ['mon'],
'timezone': 'Europe/London',
});
});
testWidgets('Cancel calls the injected callback and sends nothing', (
tester,
) async {
var cancelled = 0;
final calls = <JsonMap>[];
await pumpScheduleEditor(
tester,
draft: createDraft(name: 'Probe schedule', prompt: 'Prompt'),
onSubmit: (record) async => calls.add(record),
onCancel: () => cancelled++,
);
await tester.tap(find.byKey(scheduleEditorCancelKey));
await tester.pump();
expect(cancelled, 1);
expect(calls, isEmpty);
});
}
@@ -0,0 +1,80 @@
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/api_gateway.dart';
import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_wording.dart';
import 'schedule_editor_harness.dart';
const _labels = [
scheduleEditorNameLabel,
scheduleEditorPromptLabel,
scheduleEditorVersionLabel,
scheduleEditorWorkspaceLabel,
scheduleEditorTimerLabel,
scheduleEditorEveryLabel,
scheduleEditorDaysLabel,
scheduleEditorTimezoneLabel,
scheduleEditorEnabledLabel,
scheduleEditorEnabledNote,
scheduleEditorNotificationsLabel,
scheduleEditorSubmitLabel,
];
void main() {
testWidgets('Material labels wrap at 320px with 2x text', (tester) async {
await pumpScheduleEditor(
tester,
width: 320,
height: 1800,
textScale: 2,
draft: createDraft(),
onSubmit: (JsonMap record) async {},
);
expect(tester.takeException(), isNull);
for (final label in _labels) {
expect(find.text(label), findsOneWidget, reason: label);
}
expect(find.byType(TextField), findsNWidgets(6));
expect(find.byType(Switch), findsOneWidget);
expect(find.byType(Checkbox), findsNWidgets(7));
final note = tester.renderObject<RenderParagraph>(
find.text(scheduleEditorEnabledNote),
);
expect(note.size.width, lessThanOrEqualTo(320 - 32));
});
testWidgets('Cupertino dark uses native controls and the native palette', (
tester,
) async {
await pumpScheduleEditor(
tester,
cupertino: true,
dark: true,
width: 320,
height: 1800,
textScale: 2,
draft: createDraft(),
onSubmit: (JsonMap record) async {},
);
expect(tester.takeException(), isNull);
for (final label in _labels) {
expect(find.text(label), findsOneWidget, reason: label);
}
expect(find.byType(CupertinoTextField), findsNWidgets(6));
expect(find.byType(CupertinoSwitch), findsOneWidget);
expect(find.byType(CupertinoCheckbox), findsNWidgets(7));
expect(find.byType(Material), findsNothing);
expect(find.byType(TextField), findsNothing);
expect(find.byType(Switch), findsNothing);
expect(find.byType(Checkbox), findsNothing);
final context = tester.element(find.byKey(scheduleEditorNameKey));
expect(CupertinoTheme.of(context).brightness, Brightness.dark);
expect(
CupertinoColors.label.resolveFrom(context).toARGB32(),
CupertinoColors.label.darkColor.toARGB32(),
);
});
}
@@ -0,0 +1,104 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/templates/screen.dart';
import 'package:pipelines_app/features/templates/ui/template_create_wording.dart';
import '../data/template_test_support.dart' show source;
import 'template_gallery_test_support.dart';
Future<void> openRelease(WidgetTester tester) async {
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(templateCreateActionKey));
await tester.pumpAndSettle();
}
void main() {
testWidgets(
'Cancel sends nothing; Create validates and submits the verbatim source '
'once through the existing prompt',
(tester) async {
final gateway = GalleryGateway((type, fields) async {
if (type == 'list_templates') return templatesReply(galleryTemplates);
return acceptedCreate(type, fields);
});
final created = <JsonMap>[];
await pumpGallery(tester, gateway, onCreated: created.add);
await openRelease(tester);
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text('Create from Release workflow'), findsOneWidget);
await tester.enterText(find.byKey(templateCreateNameKey), 'Café');
await tester.pump();
await tester.tap(find.byKey(templateCreateCancelKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(gateway.callsOf('validate'), isEmpty);
expect(gateway.callsOf('submit'), isEmpty);
expect(created, isEmpty);
await tester.tap(find.byKey(templateCreateActionKey));
await tester.pumpAndSettle();
expect(find.byKey(templateCreateNameKey), findsOneWidget);
await tester.enterText(find.byKey(templateCreateNameKey), ' Café ');
await tester.pump();
await tester.tap(find.byKey(templateCreateConfirmKey));
await tester.pumpAndSettle();
expect(gateway.callsOf('validate').single.fields, {'source': source});
expect(gateway.callsOf('submit').single.fields, {
'name': 'Café',
'source': source,
'create_only': true,
});
expect(gateway.callsOf('submit').single.fields.keys, [
'name',
'source',
'create_only',
]);
expect(created, [
{'id': 7, 'name': 'Created release'},
]);
expect(
find.text('Created "Created release". It is in the Pipelines list.'),
findsOneWidget,
);
expect(find.text('Close'), findsOneWidget);
await tester.tap(find.byKey(templateCreateCancelKey));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(created, hasLength(1));
expect(gateway.callsOf('submit'), hasLength(1));
},
);
testWidgets('the callback is optional and Cupertino uses its native prompt', (
tester,
) async {
final gateway = GalleryGateway((type, fields) async {
if (type == 'list_templates') return templatesReply(galleryTemplates);
return acceptedCreate(type, fields);
});
await pumpGallery(tester, gateway, cupertino: true);
await openRelease(tester);
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
await tester.enterText(find.byKey(templateCreateNameKey), 'Cupertino');
await tester.pump();
await tester.tap(find.byKey(templateCreateConfirmKey));
await tester.pumpAndSettle();
expect(gateway.callsOf('validate'), hasLength(1));
expect(gateway.callsOf('submit'), hasLength(1));
expect(
find.text('Created "Created release". It is in the Pipelines list.'),
findsOneWidget,
);
expect(find.byKey(templateCreateCancelKey), findsOneWidget);
});
}
@@ -0,0 +1,379 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/templates/screen.dart';
import 'package:pipelines_app/features/templates/ui/template_detail.dart';
import '../data/template_test_support.dart' show source;
import 'template_gallery_test_support.dart';
void main() {
testWidgets('loading shows the exact line, then the server catalogue', (
tester,
) async {
final reply = Completer<JsonMap>();
final gateway = GalleryGateway((type, fields) => reply.future);
await pumpGallery(tester, gateway, settle: false);
await tester.pump();
expect(find.byKey(templatesLoadingKey), findsOneWidget);
expect(find.text('Loading templates…'), findsOneWidget);
expect(gateway.calls.single.type, 'list_templates');
expect(gateway.calls.single.fields, isEmpty);
reply.complete(templatesReply(galleryTemplates));
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
expect(find.text('Release workflow'), findsOneWidget);
expect(find.text('Ship a version'), findsOneWidget);
expect(find.text('(unnamed template)'), findsOneWidget);
expect(find.byKey(templatesLoadingKey), findsNothing);
});
testWidgets('an empty catalogue states it without inventing rows', (
tester,
) async {
final gateway = GalleryGateway(
(type, fields) async => templatesReply(const []),
);
await pumpGallery(tester, gateway);
expect(find.byKey(templatesEmptyKey), findsOneWidget);
expect(
find.text('No templates are available on this server.'),
findsOneWidget,
);
expect(find.byKey(templatesGalleryKey), findsNothing);
});
testWidgets('a refusal offers Retry; a failed refresh keeps the rows', (
tester,
) async {
var mode = 'refuse';
final gateway = GalleryGateway((type, fields) async {
if (type != 'list_templates') throw StateError('unexpected $type');
if (mode == 'refuse') {
throw Exception('catalogue unavailable');
}
return templatesReply(galleryTemplates);
});
await pumpGallery(tester, gateway);
expect(find.byKey(templatesErrorKey), findsOneWidget);
expect(find.text('catalogue unavailable'), findsOneWidget);
expect(find.byKey(templatesGalleryKey), findsNothing);
mode = 'ok';
await tester.tap(find.byKey(templatesRetryKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
expect(find.text('Release workflow'), findsOneWidget);
mode = 'refuse';
await tester.tap(find.byKey(templatesRefreshKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
expect(find.text('Release workflow'), findsOneWidget);
expect(find.text('catalogue unavailable'), findsOneWidget);
expect(find.byKey(templatesErrorBannerKey), findsOneWidget);
expect(find.byKey(templatesErrorKey), findsNothing);
mode = 'ok';
await tester.tap(find.byKey(templatesBannerRetryKey));
await tester.pumpAndSettle();
expect(find.text('catalogue unavailable'), findsNothing);
expect(find.byKey(templatesErrorBannerKey), findsNothing);
expect(find.text('Release workflow'), findsOneWidget);
});
testWidgets('refresh re-reads the catalogue and keeps the selection', (
tester,
) async {
var calls = 0;
final gateway = GalleryGateway((type, fields) async {
calls++;
return templatesReply(
calls == 1
? galleryTemplates
: [
...galleryTemplates,
templateJson(key: 'new', name: 'New template'),
],
);
});
await pumpGallery(tester, gateway);
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
await tester.tap(find.byKey(templatesRefreshKey));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(find.text('Release workflow'), findsOneWidget);
expect(gateway.callsOf('list_templates'), hasLength(2));
await tester.tap(find.byKey(templatesBackKey));
await tester.pumpAndSettle();
expect(find.text('New template'), findsOneWidget);
});
testWidgets('selecting a template shows metadata and verbatim source only', (
tester,
) async {
final gateway = GalleryGateway(
(type, fields) async => templatesReply(galleryTemplates),
);
await pumpGallery(tester, gateway);
expect(gateway.callsOf('list_templates'), hasLength(1));
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(find.text('Release workflow'), findsOneWidget);
expect(find.text('Ship a version'), findsOneWidget);
expect(find.text('Key'), findsOneWidget);
expect(find.text('Includes a schedule'), findsOneWidget);
expect(find.text(templateSourceLabel), findsOneWidget);
expect(selectableSource(source), findsOneWidget);
expect(selectableSource('release'), findsOneWidget);
expect(find.text(templateCreateActionLabel), findsOneWidget);
expect(gateway.callsOf('validate'), isEmpty);
expect(gateway.callsOf('submit'), isEmpty);
await tester.tap(find.byKey(templatesBackKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
expect(find.byKey(templateDetailKey), findsNothing);
});
testWidgets('native back returns to the gallery', (tester) async {
final gateway = GalleryGateway(
(type, fields) async => templatesReply(galleryTemplates),
);
await pumpGallery(tester, gateway);
await tester.tap(find.byKey(templateRowKey('blank')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(selectableSource('blank'), findsOneWidget);
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
expect(find.byKey(templateDetailKey), findsNothing);
});
testWidgets('embedded use drops the app bar and keeps native detail back', (
tester,
) async {
final gateway = GalleryGateway(
(type, fields) async => templatesReply(galleryTemplates),
);
await pumpGallery(tester, gateway, embedded: true);
expect(find.byType(AppBar), findsNothing);
expect(find.byKey(templatesRefreshKey), findsOneWidget);
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
await tester.tap(find.byKey(templateDetailBackKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
});
testWidgets('Cupertino host uses its own list, back and detail controls', (
tester,
) async {
final gateway = GalleryGateway(
(type, fields) async => templatesReply(galleryTemplates),
);
await pumpGallery(tester, gateway, cupertino: true);
expect(find.byType(CupertinoListTile), findsNWidgets(2));
expect(find.byType(Scaffold), findsNothing);
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(selectableSource(source), findsOneWidget);
expect(
tester
.widget<CupertinoButton>(find.byKey(templateCreateActionKey))
.onPressed,
isNotNull,
);
expect(find.byType(BackButton), findsNothing);
await tester.tap(find.byKey(templatesBackKey));
await tester.pumpAndSettle();
expect(find.byType(CupertinoListTile), findsNWidgets(2));
});
testWidgets(
'a failed refresh with a template open is visible and retryable',
(tester) async {
for (final cupertino in [false, true]) {
var mode = 'ok';
final gateway = GalleryGateway((type, fields) async {
if (type != 'list_templates') throw StateError('unexpected $type');
if (mode == 'refuse') throw Exception('refresh unavailable');
return templatesReply(galleryTemplates);
});
await pumpGallery(tester, gateway, cupertino: cupertino);
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
mode = 'refuse';
await tester.tap(find.byKey(templatesRefreshKey));
await tester.pumpAndSettle();
expect(gateway.callsOf('list_templates'), hasLength(2));
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(find.byKey(templatesErrorBannerKey), findsOneWidget);
expect(find.text('refresh unavailable'), findsOneWidget);
expect(find.byKey(templatesBannerRetryKey), findsOneWidget);
expect(find.byKey(templatesErrorKey), findsNothing);
expect(find.text(templateSourceLabel), findsOneWidget);
expect(find.text(templateCreateActionLabel), findsOneWidget);
expect(
tester.widget(find.byKey(templatesBannerRetryKey)),
cupertino ? isA<CupertinoButton>() : isA<TextButton>(),
);
expect(tester.takeException(), isNull);
mode = 'ok';
await tester.tap(find.byKey(templatesBannerRetryKey));
await tester.pumpAndSettle();
expect(find.text('refresh unavailable'), findsNothing);
expect(find.byKey(templatesErrorBannerKey), findsNothing);
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(find.text(templateSourceLabel), findsOneWidget);
expect(gateway.callsOf('list_templates'), hasLength(3));
await tester.tap(find.byKey(templatesBackKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
expect(find.text('Release workflow'), findsOneWidget);
expect(find.text('(unnamed template)'), findsOneWidget);
}
},
);
testWidgets('an embedded failed refresh is visible above the open template', (
tester,
) async {
var mode = 'ok';
final gateway = GalleryGateway((type, fields) async {
if (type != 'list_templates') throw StateError('unexpected $type');
if (mode == 'refuse') throw Exception('refresh unavailable');
return templatesReply(galleryTemplates);
});
await pumpGallery(tester, gateway, embedded: true);
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailBackKey), findsOneWidget);
mode = 'refuse';
await tester.tap(find.byKey(templatesRefreshKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesErrorBannerKey), findsOneWidget);
expect(find.text('refresh unavailable'), findsOneWidget);
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(find.byKey(templateDetailBackKey), findsOneWidget);
mode = 'ok';
await tester.tap(find.byKey(templatesBannerRetryKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesErrorBannerKey), findsNothing);
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(gateway.callsOf('list_templates'), hasLength(3));
});
testWidgets('2x text on a short phone has no overflow and stays reachable', (
tester,
) async {
final gateway = GalleryGateway(
(type, fields) async => templatesReply(galleryTemplates),
);
await pumpGallery(
tester,
gateway,
size: const Size(360, 640),
textScale: 2,
);
expect(tester.takeException(), isNull);
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.text(templateCreateActionLabel), findsOneWidget);
expect(selectableSource(source), findsOneWidget);
expect(find.byKey(templatesBackKey), findsOneWidget);
});
testWidgets('only the newest reply wins and a disposed screen ignores one', (
tester,
) async {
final first = Completer<JsonMap>();
final stale = Completer<JsonMap>();
var calls = 0;
final gateway = GalleryGateway((type, fields) {
calls++;
if (calls == 1) return first.future;
if (calls == 2) return stale.future;
return Future.value(
templatesReply([templateJson(key: 'fresh', name: 'Fresh')]),
);
});
await pumpGallery(tester, gateway, settle: false);
first.complete(
templatesReply([templateJson(key: 'old', name: 'Old reply')]),
);
await tester.pumpAndSettle();
expect(find.text('Old reply'), findsOneWidget);
await tester.tap(find.byKey(templatesRefreshKey));
await tester.pump();
final replacement = GalleryGateway(
(type, fields) async =>
templatesReply([templateJson(key: 'other', name: 'Other server')]),
);
await pumpGallery(tester, replacement);
expect(find.text('Other server'), findsOneWidget);
stale.complete(
templatesReply([templateJson(key: 'stale', name: 'Stale reply')]),
);
await tester.pumpAndSettle();
expect(find.text('Stale reply'), findsNothing);
expect(find.text('Other server'), findsOneWidget);
final pending = Completer<JsonMap>();
final disposedGateway = GalleryGateway((type, fields) => pending.future);
await pumpGallery(tester, disposedGateway, settle: false);
await tester.pumpWidget(const SizedBox.shrink());
pending.complete(templatesReply(galleryTemplates));
await tester.pump();
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,112 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/templates/screen.dart';
import '../data/template_test_support.dart' show source;
typedef GalleryHandler =
FutureOr<JsonMap> Function(String type, JsonMap fields);
/// A recording gateway whose replies come from [handler].
class GalleryGateway implements ApiGateway {
GalleryGateway(this.handler);
final GalleryHandler handler;
final List<({String type, JsonMap fields})> calls = [];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
final copy = Map<String, dynamic>.from(fields);
calls.add((type: type, fields: copy));
return handler(type, copy);
}
@override
Stream<JsonMap> get frames => const Stream.empty();
List<({String type, JsonMap fields})> callsOf(String type) =>
calls.where((call) => call.type == type).toList(growable: false);
}
JsonMap templateJson({
required String key,
String name = '',
String description = '',
String? definition,
bool scheduled = false,
}) => {
'key': key,
'name': name,
'description': description,
'source': definition ?? source,
'scheduled': scheduled,
};
JsonMap templatesReply(List<JsonMap> templates) => {'templates': templates};
final galleryTemplates = [
templateJson(
key: 'release',
name: 'Release workflow',
description: 'Ship a version',
scheduled: true,
),
templateJson(key: 'blank', description: 'No display name'),
];
Future<JsonMap> acceptedCreate(String type, JsonMap fields) async {
if (type == 'validate') return {'graph': {}};
if (type == 'submit') {
return {
'detail': {'id': 7, 'name': 'Created release'},
};
}
throw StateError('Unexpected request $type');
}
/// Pumps the gallery in a real Material or Cupertino host without fixed sizes.
Future<void> pumpGallery(
WidgetTester tester,
GalleryGateway gateway, {
bool cupertino = false,
bool embedded = false,
ValueChanged<JsonMap>? onCreated,
double textScale = 1,
Size size = const Size(800, 1000),
bool settle = true,
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
Widget media(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: app!,
);
final screen = TemplatesScreen(
gateway: gateway,
embedded: embedded,
onCreated: onCreated,
);
final home = embedded
? (cupertino
? CupertinoPageScaffold(child: screen)
: Scaffold(body: screen))
: screen;
await tester.pumpWidget(
cupertino
? CupertinoApp(builder: media, home: home)
: MaterialApp(builder: media, home: home),
);
if (settle) await tester.pumpAndSettle();
}
Finder selectableSource(String text) => find.byWidgetPredicate(
(widget) => widget is SelectableText && widget.data == text,
);