merge(app): land native create-from-template prompt

This commit is contained in:
2026-10-21 20:57:34 +01:00
57 changed files with 5574 additions and 381 deletions
@@ -466,7 +466,9 @@ void main() {
),
);
expect(tester.takeException(), isNull);
expect(find.text('Rendered'), findsOneWidget);
// The host is too narrow for a two-segment control at 2x, so the same form
// selection is offered through the native menu instead.
expect(find.byTooltip('Diff form'), findsOneWidget);
expect(find.text('Copy patch'), findsOneWidget);
expect(find.byTooltip('Close diff'), findsOneWidget);
});
@@ -1,5 +1,6 @@
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/changes/changes.dart';
import 'package:pipelines_app/features/changes/widgets/change_style.dart';
@@ -16,6 +17,64 @@ const _raggedPatch =
'-x\n'
' tail\n';
/// Opens the real single-file diff modal from a host, so the test covers the
/// dialog's own width and insets rather than the viewer in isolation.
Widget _diffDialogOpener(FileChange file) => Builder(
builder: (context) => TextButton(
onPressed: () => showFileDiffViewer(context, file),
child: const Text('Open diff'),
),
);
/// Fails when a fixed control label is broken inside a word or clipped by its
/// control. A label may wrap only between whole words, which is how a native
/// menu keeps an accessibility-size label readable.
void _expectWholeLabel(WidgetTester tester, Finder finder, String label) {
final paragraph = tester.renderObject<RenderParagraph>(
find.descendant(of: finder, matching: find.byType(RichText)),
);
final span = paragraph.text as TextSpan;
expect(span.toPlainText(), label);
expect(paragraph.didExceedMaxLines, isFalse);
final boxes = paragraph
.getBoxesForSelection(
TextSelection(baseOffset: 0, extentOffset: label.length),
)
.toList();
expect(boxes, isNotEmpty);
// The laid-out paragraph must be tall enough to paint every line it broke.
expect(
boxes.last.bottom,
lessThanOrEqualTo(paragraph.size.height + 0.5),
reason: '"$label" must not be clipped vertically',
);
final widestLine = boxes
.map((box) => box.right - box.left)
.reduce((a, b) => a > b ? a : b);
final style = span.style ?? const TextStyle();
var widestWord = 0.0;
for (final word in label.split(' ')) {
final painter = TextPainter(
text: TextSpan(text: word, style: style),
textDirection: TextDirection.ltr,
textScaler: paragraph.textScaler,
)..layout();
if (painter.width > widestWord) widestWord = painter.width;
}
// A line narrower than a whole word means the label broke mid-word.
expect(
widestLine,
greaterThanOrEqualTo(widestWord - 0.5),
reason: '"$label" must not break inside a word',
);
// A clipped line would paint wider than the paragraph's laid-out box.
expect(
widestLine,
lessThanOrEqualTo(paragraph.size.width + 0.5),
reason: '"$label" must not be clipped horizontally',
);
}
void main() {
test(
'patch typography preserves the native host style without overrides',
@@ -139,6 +198,49 @@ void main() {
);
});
testWidgets('the Cupertino raw patch is a native selectable field', (
tester,
) async {
await tester.pumpWidget(
cupertinoHost(
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();
// A CupertinoApp has no MaterialLocalizations, so Raw must not use the
// Material SelectionArea; it renders the recorded bytes in a native field.
expect(tester.takeException(), isNull);
expect(find.byType(SelectionArea), findsNothing);
final field = tester.widget<CupertinoTextField>(
find.byKey(const ValueKey('raw-patch-field')),
);
expect(field.readOnly, isTrue);
expect(field.maxLines, isNull);
expect(field.controller?.text, multiHunkPatch);
expect(
find.ancestor(
of: find.byKey(const ValueKey('raw-patch-field')),
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 {
@@ -203,4 +305,98 @@ void main() {
expect(rect.right, lessThan(382));
expect(tester.takeException(), isNull);
});
final diffFile = FileChange(
path: 'lib/feature.dart',
kind: ChangeKind.modified,
patch: multiHunkPatch,
);
for (final cupertino in [false, true]) {
final host = cupertino ? 'Cupertino' : 'Material';
testWidgets('$host diff labels stay whole at 320x720 with 2x text', (
tester,
) async {
tester.view.physicalSize = const Size(320, 720);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final opener = _diffDialogOpener(diffFile);
await tester.pumpWidget(
cupertino
? cupertinoHost(opener, scaler: const TextScaler.linear(2))
: materialHost(opener, scaler: const TextScaler.linear(2)),
);
await tester.tap(find.text('Open diff'));
await tester.pumpAndSettle();
// A segmented control cannot keep both fixed words at this size, so the
// host's native menu carries them instead. "Rendered" used to break
// mid-word and "Raw patch" used to be clipped to "Raw".
expect(find.byType(SegmentedButton<DiffForm>), findsNothing);
expect(
find.byType(CupertinoSlidingSegmentedControl<DiffForm>),
findsNothing,
);
// Copy patch stays a standard action at intrinsic width; it must not
// break its two words either.
_expectWholeLabel(tester, find.text('Copy patch'), 'Copy patch');
await tester.tap(
cupertino
? find.byIcon(CupertinoIcons.ellipsis)
: find.byTooltip('Diff form'),
);
await tester.pumpAndSettle();
final items = cupertino
? find.byType(CupertinoActionSheetAction)
: find.byType(ListTile);
expect(items, findsNWidgets(2));
for (final label in ['Rendered', 'Raw patch']) {
_expectWholeLabel(
tester,
find.descendant(of: items, matching: find.text(label)),
label,
);
}
await tester.tap(
find.descendant(of: items, matching: find.text('Raw patch')),
);
await tester.pumpAndSettle();
if (cupertino) {
expect(find.byKey(const ValueKey('raw-patch-field')), findsOneWidget);
} else {
expect(find.text(multiHunkPatch), findsOneWidget);
}
expect(tester.takeException(), isNull);
});
}
for (final cupertino in [false, true]) {
testWidgets(
'${cupertino ? 'Cupertino' : 'Material'} wide host keeps the native '
'segmented control',
(tester) async {
await tester.pumpWidget(
cupertino
? cupertinoHost(_diffDialogOpener(diffFile))
: materialHost(_diffDialogOpener(diffFile)),
);
await tester.tap(find.text('Open diff'));
await tester.pumpAndSettle();
expect(
cupertino
? find.byType(CupertinoSlidingSegmentedControl<DiffForm>)
: find.byType(SegmentedButton<DiffForm>),
findsOneWidget,
);
expect(find.text('Rendered'), findsOneWidget);
expect(find.text('Raw patch'), findsOneWidget);
expect(tester.takeException(), isNull);
},
);
}
}
@@ -415,6 +415,15 @@ void main() {
);
});
test('showRunChangesSummary is true only for a settled succeeded run', () {
expect(showRunChangesSummary('succeeded'), isTrue);
expect(showRunChangesSummary(' Succeeded '), isTrue);
for (final status in ['failed', 'running', 'waiting', 'canceled', '']) {
expect(showRunChangesSummary(status), isFalse, reason: status);
}
expect(showRunChangesSummary(null), isFalse);
});
test('header covers every empty-capture variant', () {
expect(
runChangesHeader(_run(unavailable: true, files: const [])),
@@ -0,0 +1,154 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
import 'chat_thread_fixtures.dart';
void main() {
late FakeChatGateway gateway;
late ChatThreadController controller;
setUp(() {
gateway = FakeChatGateway();
controller = ChatThreadController(gateway, 's');
});
tearDown(() {
controller.dispose();
gateway.close();
});
test(
'subscribes the exact session, then reads newest history with all data',
() async {
final unknown = chatMessage(
'a',
'assistant',
parts: [
{
'type': 'future_part',
'id': 'p1',
'payload': {'nested': true},
'unknown_field': 7,
},
],
)..['future_message_field'] = 'keep';
gateway.history = (_) async =>
chatPage([unknown], cursor: 'opaque/next?x=1', hasMore: true);
await controller.load();
expect(gateway.calls.map((call) => call.type), [
'chat_subscribe',
'chat_messages',
]);
expect(gateway.calls.first.fields, {
'chat_subscribe': {'session_id': 's'},
});
expect(gateway.calls.last.fields['chat_query'], {
'session_id': 's',
'limit': 200,
'cursor': '',
});
expect(controller.loaded, isTrue);
expect(controller.loading, isFalse);
expect(controller.error, isNull);
expect(controller.running, isFalse);
expect(controller.hasMore, isTrue);
expect(controller.cursor, 'opaque/next?x=1');
expect(controller.messages.single, unknown);
expect(controller.messages.single['future_message_field'], 'keep');
},
);
test(
'loadOlder passes the opaque cursor back and prepends the page',
() async {
gateway.history = (_) async => chatPage(
[chatMessage('b', 'user')],
cursor: 'older-1',
hasMore: true,
);
await controller.load();
final olderReply = Completer<JsonMap>();
gateway.history = (_) => olderReply.future;
final loadingStates = <bool>[];
controller.addListener(() => loadingStates.add(controller.loading));
final older = controller.loadOlder();
expect(gateway.calls.last.fields['chat_query'], {
'session_id': 's',
'limit': 200,
'cursor': 'older-1',
});
expect(controller.loading, isTrue);
expect(loadingStates, [true]);
olderReply.complete(
chatPage(
[chatMessage('a', 'assistant')],
cursor: 'last',
hasMore: false,
),
);
await older;
expect(controller.messages.map((item) => item['id']), ['a', 'b']);
expect(controller.cursor, 'last');
expect(controller.hasMore, isFalse);
expect(controller.loading, isFalse);
},
);
test(
'a superseded history reply never replaces the newer transcript',
() async {
final first = Completer<JsonMap>();
final second = Completer<JsonMap>();
var request = 0;
gateway.history = (_) => request++ == 0 ? first.future : second.future;
final stale = controller.load();
await pumpEventQueue();
final current = controller.load();
await pumpEventQueue();
second.complete(chatPage([chatMessage('new', 'user')]));
await current;
expect(controller.messages.single['id'], 'new');
first.complete(chatPage([chatMessage('old', 'user')]));
await stale;
expect(controller.messages.single['id'], 'new');
expect(controller.loaded, isTrue);
expect(controller.loading, isFalse);
},
);
test(
'a failed history read reports the error, never an empty success',
() async {
gateway.history = (_) => Future.error(StateError('history unavailable'));
await controller.load();
expect(controller.error, contains('history unavailable'));
expect(controller.error, isNot(''));
expect(controller.messages, isEmpty);
expect(controller.loading, isFalse);
expect(controller.loaded, isTrue);
},
);
test('a refused subscribe leaves history usable', () async {
gateway.subscribe = () => Future.error(StateError('not live'));
gateway.history = (_) async => chatPage([chatMessage('a', 'user')]);
await controller.load();
expect(controller.messages.single['id'], 'a');
expect(controller.error, isNull);
expect(controller.loaded, isTrue);
});
}
@@ -0,0 +1,73 @@
import 'dart:async';
import 'package:pipelines_app/core/api_gateway.dart';
/// A fake gateway whose subscribe/history replies the test controls.
class FakeChatGateway implements ApiGateway {
final calls = <({String type, JsonMap fields})>[];
final historyRequests = <Completer<JsonMap>>[];
final _frames = StreamController<JsonMap>.broadcast();
Future<JsonMap> Function(JsonMap fields)? history;
Future<JsonMap> Function()? subscribe;
void Function()? onSubscribe;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add((type: type, fields: fields));
switch (type) {
case 'chat_subscribe':
onSubscribe?.call();
return subscribe == null ? <String, dynamic>{} : subscribe!();
case 'chat_messages':
final completer = Completer<JsonMap>();
historyRequests.add(completer);
if (history != null) return history!(fields);
return completer.future;
}
return <String, dynamic>{};
}
@override
Stream<JsonMap> get frames => _frames.stream;
void emitEvent(JsonMap body) {
_frames.add({'type': 'chat_event', 'chat_event': body});
}
void emitRaw(JsonMap envelope) => _frames.add(envelope);
void close() => _frames.close();
}
JsonMap chatPage(
List<JsonMap> messages, {
String cursor = '',
bool hasMore = false,
}) => {
'chat_history': {
'messages': messages,
'next_cursor': cursor,
'has_more': hasMore,
},
};
JsonMap chatMessage(String id, String role, {List<JsonMap> parts = const []}) =>
{'id': id, 'role': role, 'parts': parts};
JsonMap chatTextFrame(
String text, {
String session = 's',
String messageId = 'a',
}) => {
'session_id': session,
'message_id': messageId,
'kind': 'text',
'part': {'id': 'p', 'type': 'text'},
'delta': text,
};
JsonMap chatStepFrame(String status, {String session = 's'}) => {
'session_id': session,
'kind': 'step',
'step': {'status': status, 'turn_id': 'turn', 'intermediate': false},
};
@@ -0,0 +1,188 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
import 'chat_thread_fixtures.dart';
void main() {
late FakeChatGateway gateway;
late ChatThreadController controller;
setUp(() {
gateway = FakeChatGateway();
controller = ChatThreadController(gateway, 's');
});
tearDown(() {
controller.dispose();
gateway.close();
});
test('folds own session frames only and keeps live turn activity', () async {
gateway.history = (_) async => chatPage([
chatMessage(
'a',
'assistant',
parts: [
{'type': 'reasoning', 'id': 'r', 'text': 'held'},
],
),
]);
await controller.load();
var notifications = 0;
controller.addListener(() => notifications++);
gateway.emitEvent(chatTextFrame('foreign', session: 'other'));
gateway.emitEvent(chatTextFrame('nodata')..remove('session_id'));
gateway.emitRaw({'type': 'run_event', 'session_id': 's'});
await pumpEventQueue();
expect(notifications, 0);
expect(controller.messages.single['parts'], [
{'type': 'reasoning', 'id': 'r', 'text': 'held'},
]);
expect(controller.running, isFalse);
gateway.emitEvent(chatTextFrame('one'));
gateway.emitEvent(chatTextFrame(' two'));
await pumpEventQueue();
expect(controller.running, isTrue);
expect(controller.messages.single['parts'], [
{'type': 'reasoning', 'id': 'r', 'text': 'held'},
{'type': 'text', 'id': 'p', 'text': 'one two'},
]);
gateway.emitEvent(chatStepFrame('ended'));
await pumpEventQueue();
expect(controller.running, isFalse);
expect(notifications, greaterThan(0));
});
test(
'resync re-subscribes, settles the held turn, and replaces it with the page',
() async {
gateway.history = (_) async => chatPage(
[
chatMessage('stale-user', 'user'),
chatMessage('stale-assistant', 'assistant'),
],
cursor: 'stale-cursor',
hasMore: true,
);
await controller.load();
gateway.emitEvent(chatTextFrame('still running'));
await pumpEventQueue();
expect(controller.running, isTrue);
gateway.onSubscribe = () {
// Settled before the re-attach, then replay proves the fresh turn.
expect(controller.running, isFalse);
gateway.emitEvent(chatStepFrame('started'));
};
gateway.history = (_) async => chatPage(
[
chatMessage('fresh-user', 'user'),
chatMessage('fresh-assistant', 'assistant'),
],
cursor: 'fresh-cursor',
hasMore: false,
);
await controller.resync();
await pumpEventQueue();
expect(
gateway.calls.where((call) => call.type == 'chat_subscribe').length,
2,
);
expect(
gateway.calls.where((call) => call.type == 'chat_messages').length,
2,
);
expect(gateway.calls.last.fields['chat_query'], {
'session_id': 's',
'limit': 200,
'cursor': '',
});
expect(controller.messages.map((item) => item['id']), [
'fresh-user',
'fresh-assistant',
]);
expect(controller.cursor, 'fresh-cursor');
expect(controller.hasMore, isFalse);
expect(controller.running, isTrue);
expect(controller.error, isNull);
},
);
test(
'a failed resync keeps replayed activity and reports the error',
() async {
var attempt = 0;
gateway.history = (_) async {
attempt++;
if (attempt == 1) return chatPage([chatMessage('held', 'user')]);
throw StateError('resync unavailable');
};
await controller.load();
gateway.onSubscribe = () {
gateway.emitEvent(chatStepFrame('started'));
};
await controller.resync();
await pumpEventQueue();
expect(controller.messages.single['id'], 'held');
expect(controller.running, isTrue);
expect(controller.error, contains('resync unavailable'));
expect(controller.loading, isFalse);
},
);
test(
'a resync frame reattaches and replaces the new authoritative page',
() async {
var attempt = 0;
gateway.history = (_) async => attempt++ == 0
? chatPage([chatMessage('held', 'user')], hasMore: true)
: chatPage([chatMessage('fresh', 'assistant')]);
await controller.load();
gateway.emitEvent({'session_id': 's', 'kind': 'resync'});
await pumpEventQueue();
expect(
gateway.calls.where((call) => call.type == 'chat_subscribe').length,
2,
);
expect(controller.messages.single['id'], 'fresh');
expect(controller.hasMore, isFalse);
},
);
test(
'disposal ignores a late reply and never invents an unsubscribe',
() async {
final pending = Completer<JsonMap>();
gateway.history = (_) => pending.future;
var notifications = 0;
controller.addListener(() => notifications++);
final load = controller.load();
await pumpEventQueue();
final before = notifications;
controller.dispose();
pending.complete(chatPage([chatMessage('late', 'user')]));
await load;
expect(notifications, before);
expect(
gateway.calls.where((call) => call.type == 'chat_unsubscribe'),
isEmpty,
);
// Keep tearDown's dispose idempotent.
controller = ChatThreadController(gateway, 's');
},
);
}
@@ -0,0 +1,27 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
import 'chat_thread_fixtures.dart';
void main() {
test('readable history never hides a refused live subscription', () async {
final gateway = FakeChatGateway();
gateway.subscribe = () async {
throw StateError('live watch denied');
};
gateway.history = (_) async =>
chatPage([chatMessage('stored', 'assistant')]);
addTearDown(gateway.close);
final controller = ChatThreadController(gateway, 's');
addTearDown(controller.dispose);
await controller.load();
expect(controller.messages.single['id'], 'stored');
expect(controller.error, isNull);
expect(controller.subscribed, isFalse);
expect(controller.subscriptionError, contains('live watch denied'));
gateway.subscribe = () async => {};
await controller.resync();
expect(controller.subscribed, isTrue);
expect(controller.subscriptionError, isNull);
});
}
@@ -128,6 +128,32 @@ void main() {
expect(find.text('Alpha review'), findsOneWidget);
});
testWidgets('embedded framing adds no bar and keeps a content refresh', (
tester,
) async {
final fixture = PipelineFixture();
final gateway = gatewayFor(fixture);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Host bar')),
body: PipelinesScreen(gateway: gateway, embedded: true),
),
),
);
await tester.pumpAndSettle();
expect(find.byType(AppBar), findsOneWidget);
expect(find.text('Host bar'), findsOneWidget);
expect(find.text('Pipelines'), findsNothing);
expect(find.text('Alpha review'), findsOneWidget);
final lists = gateway.callsOf('list_pipelines').length;
await tester.tap(find.byTooltip('Refresh'));
await tester.pumpAndSettle();
expect(gateway.callsOf('list_pipelines').length, lists + 1);
});
testWidgets('graph tab states it is pending without a hook', (tester) async {
final fixture = PipelineFixture();
await pumpWide(tester, gatewayFor(fixture));
@@ -0,0 +1,93 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/actions/cancel_wording.dart';
import 'package:pipelines_app/features/runs/screen.dart';
class _Gateway implements ApiGateway {
final events = StreamController<JsonMap>.broadcast();
final requests = <({String type, JsonMap fields})>[];
final canceled = Completer<JsonMap>();
final JsonMap run = {
'id': 7,
'title': 'Controlled run',
'name': 'fixture',
'status': 'running',
'executing': true,
'steps': <JsonMap>[],
};
@override
Stream<JsonMap> get frames => events.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
requests.add((type: type, fields: fields));
return switch (type) {
'list_runs' => Future.value({
'runs': [Map.of(run)],
}),
'get_run' => Future.value({'run_detail': Map.of(run)}),
'cancel_run' => canceled.future,
_ => Future.error(UnsupportedError(type)),
};
}
}
void main() {
for (final cupertino in [false, true]) {
testWidgets(
'actual detail confirms cancel and folds accepted state ($cupertino)',
(tester) async {
final gateway = _Gateway();
addTearDown(gateway.events.close);
final screen = RunsScreen(gateway: gateway, initialRunId: 7);
await tester.pumpWidget(
cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: screen))
: MaterialApp(home: Scaffold(body: screen)),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
expect(find.text('Cancel run 7?'), findsOneWidget);
expect(gateway.requests.where((r) => r.type == 'cancel_run'), isEmpty);
await tester.tap(find.byKey(cancelKeepKey));
await tester.pumpAndSettle();
expect(gateway.requests.where((r) => r.type == 'cancel_run'), isEmpty);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(cancelConfirmKey));
await tester.pump();
expect(
gateway.requests.where((r) => r.type == 'cancel_run').single.fields,
{'run_id': 7},
);
expect(find.text('canceled'), findsNothing);
gateway.canceled.complete({
'run_detail': {
...gateway.run,
'status': 'canceled',
'executing': false,
},
});
await tester.pumpAndSettle();
expect(find.byKey(cancelActionKey), findsNothing);
expect(find.text('canceled'), findsOneWidget);
await tester.tap(find.text(cupertino ? 'Back' : 'Back to list'));
await tester.pumpAndSettle();
expect(
find.textContaining('canceled'),
findsWidgets,
reason:
'The accepted server state must also update the held list row',
);
await tester.pumpWidget(const SizedBox.shrink());
},
);
}
}
@@ -0,0 +1,177 @@
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/changes/changes.dart';
import 'package:pipelines_app/features/runs/data/runs_repository.dart';
import 'package:pipelines_app/features/runs/ui/run_changes_action.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_view.dart';
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
import '../../changes/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({
JsonMap? fileChanges,
String status = 'succeeded',
String stepStatus = 'completed',
}) => {
'id': 9,
'title': 'Wiring run',
'name': 'release',
'status': status,
'steps': [
stepFixture(
stage: 'implementer',
sequence: 1,
status: stepStatus,
fileChanges: fileChanges,
),
stepFixture(
stage: 'reviewer',
sequence: 2,
status: stepStatus,
fileChanges: null,
),
],
};
Future<void> _pumpDetail(
WidgetTester tester,
_Platform platform,
RunsController controller,
) async {
tester.view.physicalSize = const Size(500, 1200);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final view = RunDetailView(controller: controller, onBack: () {});
await tester.pumpWidget(
platform == _Platform.material
? MaterialApp(home: Scaffold(body: view))
: CupertinoApp(
// The real host chooses Cupertino on iOS/macOS; state that platform
// without mutating the global debug override, as the Changes tests do.
builder: (context, app) => Theme(
data: ThemeData(platform: TargetPlatform.iOS),
child: app!,
),
home: CupertinoPageScaffold(child: view),
),
);
await tester.pumpAndSettle();
}
void main() {
for (final platform in _Platform.values) {
testWidgets(
'${platform.name}: Changes opens the recorded files, diff and returns',
(tester) async {
final controller = RunsController(
RunsRepository(
_FakeGateway(
_run(
fileChanges: captureFixture(
files: [
fileChangeFixture(
path: 'lib/feature.dart',
patch: multiHunkPatch,
),
],
),
),
),
),
);
addTearDown(controller.dispose);
await controller.select(9);
await _pumpDetail(tester, platform, controller);
await tester.tap(find.byKey(runChangesButtonKey));
await tester.pumpAndSettle();
expect(find.text('Changes'), findsOneWidget);
expect(find.text('lib/feature.dart'), findsOneWidget);
expect(
find.text('1 file changed · +2 -2 · capture incomplete'),
findsOneWidget,
);
// Visit numbers are per stage, so both stages' first visits say Visit 1.
expect(find.text('Visit 1 · completed'), findsNWidgets(2));
await tester.tap(
find.byKey(const ValueKey('change-1-lib/feature.dart')),
);
await tester.pumpAndSettle();
final rendered = tester
.widgetList<RichText>(find.byType(RichText))
.map((rich) => rich.text.toPlainText())
.join('\n');
expect(rendered, contains('+ added line'));
expect(rendered, contains('- removed line'));
if (platform == _Platform.material) {
await tester.tap(find.byTooltip('Close diff'));
} else {
await tester.tap(find.byIcon(CupertinoIcons.xmark));
}
await tester.pumpAndSettle();
expect(find.text('lib/feature.dart'), findsOneWidget);
if (platform == _Platform.material) {
await tester.tap(find.byTooltip('Back'));
} else {
await tester.tap(find.byType(CupertinoNavigationBarBackButton));
}
await tester.pumpAndSettle();
expect(find.text('Wiring run'), findsOneWidget);
expect(find.byKey(runChangesButtonKey), findsOneWidget);
expect(find.text('lib/feature.dart'), findsNothing);
},
);
testWidgets(
'${platform.name}: an unavailable capture keeps its gap wording',
(tester) async {
final diagnostic =
'Workspace snapshot unavailable; changes could not be compared.';
final controller = RunsController(
RunsRepository(
_FakeGateway(
_run(
fileChanges: captureFixture(
status: 'unavailable',
diagnostic: diagnostic,
),
),
),
),
);
addTearDown(controller.dispose);
await controller.select(9);
await _pumpDetail(tester, platform, controller);
await tester.tap(find.byKey(runChangesButtonKey));
await tester.pumpAndSettle();
expect(find.text('Changes · capture unavailable'), findsOneWidget);
expect(find.text(diagnostic), findsWidgets);
expect(find.text(emptyCaptureDetail), findsNothing);
expect(find.text('No changes observed'), findsNothing);
},
);
}
}
@@ -0,0 +1,204 @@
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/run_changes_action.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_view.dart';
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
import '../../changes/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 String status,
JsonMap? fileChanges,
String stepStatus = 'completed',
}) => {
'id': 9,
'title': 'Wiring run',
'name': 'release',
'status': status,
'steps': [
stepFixture(
stage: 'implementer',
sequence: 1,
status: stepStatus,
fileChanges: fileChanges,
),
stepFixture(
stage: 'reviewer',
sequence: 2,
status: stepStatus,
fileChanges: null,
),
],
};
Future<void> _pumpDetail(
WidgetTester tester,
_Platform platform,
JsonMap run, {
Brightness brightness = Brightness.light,
}) async {
tester.view.physicalSize = const Size(500, 1200);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final controller = RunsController(RunsRepository(_FakeGateway(run)));
addTearDown(controller.dispose);
await controller.select(9);
final view = RunDetailView(controller: controller, onBack: () {});
await tester.pumpWidget(
platform == _Platform.material
? MaterialApp(
theme: ThemeData(brightness: brightness),
home: Scaffold(body: view),
)
: CupertinoApp(
theme: CupertinoThemeData(brightness: brightness),
builder: (context, app) => Theme(
data: ThemeData(platform: TargetPlatform.iOS),
child: app!,
),
home: CupertinoPageScaffold(child: view),
),
);
await tester.pumpAndSettle();
}
Future<void> _openChanges(
WidgetTester tester,
_Platform platform,
JsonMap run, {
Brightness brightness = Brightness.light,
}) async {
await _pumpDetail(tester, platform, run, brightness: brightness);
await tester.tap(find.byKey(runChangesButtonKey));
await tester.pumpAndSettle();
}
void main() {
test('the Changes action waits for the run to stop executing', () {
for (final status in ['queued', 'running', 'waiting', ' RUNNING ']) {
expect(showRunChangesAction({'status': status}), isFalse, reason: status);
}
for (final status in ['succeeded', 'failed', 'canceled', 'interrupted']) {
expect(showRunChangesAction({'status': status}), isTrue, reason: status);
}
// The server can keep a failed run flagged while one of its steps is still
// active; the snapshot page would go stale, so the flag wins.
expect(
showRunChangesAction({'status': 'failed', 'executing': true}),
isFalse,
);
expect(
showRunChangesAction({'status': 'succeeded', 'executing': false}),
isTrue,
);
});
for (final platform in _Platform.values) {
testWidgets(
'${platform.name}: a failed run keeps visit evidence, not a summary',
(tester) async {
await _openChanges(
tester,
platform,
_run(
status: 'failed',
fileChanges: captureFixture(
files: [fileChangeFixture(path: 'lib/feature.dart')],
),
),
);
// The web client shows the aggregate only for succeeded runs.
expect(find.textContaining('file changed ·'), findsNothing);
expect(
find.textContaining('The summary counts each path once'),
findsNothing,
);
// The visit's own recorded capture stays reachable.
expect(find.text('lib/feature.dart'), findsOneWidget);
expect(find.text('Visit 1 · completed'), findsNWidgets(2));
expect(tester.takeException(), isNull);
},
);
testWidgets(
'${platform.name}: an active run offers no snapshot Changes page',
(tester) async {
await _pumpDetail(
tester,
platform,
_run(status: 'running', stepStatus: 'running'),
);
// The opened page would not follow live captures, so an executing run
// has no action until the live visit pane can show them.
expect(find.byKey(runChangesButtonKey), findsNothing);
expect(find.text('Changes'), findsNothing);
expect(tester.takeException(), isNull);
},
);
testWidgets(
'${platform.name}: the Changes page follows a dark host theme',
(tester) async {
await _openChanges(
tester,
platform,
_run(
status: 'succeeded',
fileChanges: captureFixture(
files: [fileChangeFixture(path: 'lib/feature.dart')],
),
),
brightness: Brightness.dark,
);
final header = tester.widget<Text>(
find.textContaining('1 file changed'),
);
final color = header.style?.color;
expect(color, isNotNull);
expect(
color!.computeLuminance(),
greaterThan(0.5),
reason: 'section text must be light on a dark host: $color',
);
// The diff opens on the app Navigator, above the page's theme, so its
// own header must follow the host brightness too.
await tester.tap(
find.byKey(const ValueKey('change-1-lib/feature.dart')),
);
await tester.pumpAndSettle();
final title = tester.widget<Text>(find.text('Modified'));
final titleColor = title.style?.color;
expect(titleColor, isNotNull);
expect(
titleColor!.computeLuminance(),
greaterThan(0.5),
reason: 'diff header must be light on a dark host: $titleColor',
);
expect(tester.takeException(), isNull);
},
);
}
}
@@ -0,0 +1,109 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/actions/decision_wording.dart';
import 'package:pipelines_app/features/runs/screen.dart';
class _DecisionGateway implements ApiGateway {
final events = StreamController<JsonMap>.broadcast();
final decisions = <JsonMap>[];
final reply = Completer<JsonMap>();
final JsonMap run = {
'id': 9,
'title': 'Human checkpoint',
'name': 'fixture',
'status': 'waiting',
'executing': false,
'current_stage': 'gate',
'graph': {
'stages': [
{
'key': 'gate',
'type': 'human',
'edges': {'approve': '#success'},
},
],
},
'steps': [
{
'sequence': 1,
'stage': 'gate',
'status': 'waiting',
'output': {
'prompt': 'Please review this recorded checkpoint.',
'options': ['approve'],
},
},
],
};
@override
Stream<JsonMap> get frames => events.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) =>
switch (type) {
'list_runs' => Future.value({
'runs': [run],
}),
'get_run' => Future.value({'run_detail': run}),
'decide_run' => _decide(fields),
_ => Future.error(UnsupportedError(type)),
};
Future<JsonMap> _decide(JsonMap fields) {
decisions.add(fields);
return reply.future;
}
}
void main() {
for (final cupertino in [false, true]) {
testWidgets(
'actual detail exposes and confirms recorded decision ($cupertino)',
(tester) async {
final gateway = _DecisionGateway();
addTearDown(gateway.events.close);
final screen = RunsScreen(gateway: gateway, initialRunId: 9);
await tester.pumpWidget(
cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: screen))
: MaterialApp(home: Scaffold(body: screen)),
);
await tester.pumpAndSettle();
expect(find.text(decisionWaitingTitle), findsOneWidget);
await tester.tap(find.byKey(decisionActionKey));
await tester.pumpAndSettle();
expect(
find.text('Please review this recorded checkpoint.'),
findsOneWidget,
);
await tester.tap(find.text('approve'));
await tester.enterText(find.byKey(decisionFeedbackKey), ' checked ');
await tester.pump();
expect(gateway.decisions, isEmpty);
await tester.tap(find.text(decisionConfirmLabel));
await tester.pump();
expect(gateway.decisions.single, {
'run_id': 9,
'stage': 'gate',
'option': 'approve',
'feedback': 'checked',
});
gateway.reply.complete({
'run_detail': {
...gateway.run,
'status': 'succeeded',
'executing': false,
},
});
await tester.pumpAndSettle();
expect(find.byKey(decisionActionKey), findsNothing);
expect(find.text(decisionWaitingTitle), findsNothing);
expect(find.text('succeeded'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
},
);
}
}
@@ -0,0 +1,42 @@
import 'dart:convert';
import 'package:pipelines_app/core/api_gateway.dart';
JsonMap deepCopy(JsonMap value) => jsonDecode(jsonEncode(value)) as JsonMap;
/// A server record with every editable field plus unknown record, input, rule
/// and run-option keys this slice must preserve.
JsonMap completeRecord() => {
'id': 9,
'revision': 13,
'name': 'Saved topic',
'pipeline_id': 4,
'version': 2,
'enabled': true,
'input': {
'prompt': 'Topic',
'count': 4,
'flag': false,
'nested': {
'list': [null, 2],
},
},
'workspace': '/srv/research',
'rule': {
'times': ['09:00', '17:30'],
'days': ['fri', 'mon'],
'timezone': '',
'future': 'keep',
},
'model': 'provider/model',
'stage_models': {'research': 'provider/other'},
'write_paths': ['src/file.go'],
'allow_tools': true,
'title': 'Saved title',
'output_format': 'json',
'notify_mode': 'off',
'next_due': '2026-10-22T09:00:00Z',
'server_extra': {
'keep': [1, true],
},
};
@@ -0,0 +1,30 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/schedules/domain/editor/schedule_draft.dart';
import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart';
import 'draft_fixtures.dart';
void main() {
test('an invalid pipeline identity cannot become a create payload', () {
final draft =
ScheduleDraft.create(pipelineId: 0, version: '1', workspace: '/srv')
..name = 'Topic'
..prompt = 'Research this';
expect(draft.build().record, isNull);
expect(draft.build().errors, contains('pipelineId'));
});
for (final missing in ['id', 'revision']) {
test(
'missing $missing never turns an edit into an unconditional create',
() {
final raw = completeRecord()..remove(missing);
final source = SavedSchedule(raw);
final draft = ScheduleDraft.fromSchedule(source);
expect(draft.build().record, isNull);
expect(draft.build().errors, contains('record'));
expect(source.raw.containsKey(missing), isFalse);
},
);
}
}
@@ -0,0 +1,134 @@
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 'draft_fixtures.dart';
void main() {
test('a new schedule snapshots prompt, pipeline, workspace and version', () {
final draft =
ScheduleDraft.create(
pipelineId: 42,
version: '7',
workspace: '/srv/research',
timezone: 'UTC',
)
..name = 'AI news'
..prompt = 'Research AI news';
final result = draft.build();
expect(result.isValid, isTrue);
expect(result.errors, isEmpty);
final record = result.record!;
expect(record['id'], 0);
expect(record.containsKey('revision'), isFalse);
expect(record['pipeline_id'], 42);
expect(record['version'], 7);
expect(record['enabled'], isTrue);
expect(record['name'], 'AI news');
expect(record['workspace'], '/srv/research');
expect(record['input'], {'prompt': 'Research AI news'});
expect(record['rule'], {'every': '24h', 'timezone': 'UTC'});
expect(record['notify_mode'], 'auto');
});
test('an edit preserves CAS, unknown fields and untouched run options', () {
final original = completeRecord();
final snapshot = deepCopy(original);
final schedule = SavedSchedule(original);
final draft = ScheduleDraft.fromSchedule(schedule)..prompt = 'Changed';
final result = draft.build();
expect(result.isValid, isTrue);
final record = result.record!;
expect(record['id'], 9);
expect(record['revision'], 13);
expect(record['workspace'], '/srv/research');
expect(record['server_extra'], snapshot['server_extra']);
expect(record['next_due'], snapshot['next_due']);
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['input'] as JsonMap)['count'], 4);
expect((record['input'] as JsonMap)['nested'], {
'list': [null, 2],
});
expect((record['input'] as JsonMap)['prompt'], 'Changed');
expect((record['rule'] as JsonMap)['future'], 'keep');
expect((record['rule'] as JsonMap)['days'], ['fri', 'mon']);
// Neither the server map nor the SavedSchedule snapshot was mutated.
expect(original, snapshot);
expect(schedule.toJson(), snapshot);
((record['input'] as JsonMap)['nested'] as JsonMap)['extra'] = true;
expect(schedule.input['nested'], {
'list': [null, 2],
});
});
test(
'an edit writes the changed workspace, untrimmed like the web client',
() {
final record = (ScheduleDraft.fromSchedule(
SavedSchedule(completeRecord()),
)..workspace = '/srv/other').build().record!;
expect(record['workspace'], '/srv/other');
final untrimmed = (ScheduleDraft.fromSchedule(
SavedSchedule(completeRecord()),
)..workspace = '/srv/dir ').build().record!;
expect(untrimmed['workspace'], '/srv/dir ');
},
);
test('a prompt-only edit keeps the existing weekday order', () {
final original = completeRecord();
final draft = ScheduleDraft.fromSchedule(SavedSchedule(original))
..prompt = 'New topic'
..days = ['mon', 'fri'];
final record = draft.build().record!;
expect((record['rule'] as JsonMap)['days'], ['fri', 'mon']);
expect((record['rule'] as JsonMap)['times'], ['09:00', '17:30']);
expect((record['rule'] as JsonMap)['timezone'], isNull);
});
test('switching modes removes the other timer shape and keeps unknowns', () {
final original = completeRecord();
final clock = ScheduleDraft.fromSchedule(SavedSchedule(original))
..mode = ScheduleTimerMode.clock
..times = '09:00, 23:59';
final clockRule = clock.build().record!['rule'] as JsonMap;
expect(clockRule['times'], ['09:00', '23:59']);
expect(clockRule.containsKey('every'), isFalse);
expect(clockRule['future'], 'keep');
final interval =
ScheduleDraft.fromSchedule(SavedSchedule(clock.build().record!))
..mode = ScheduleTimerMode.interval
..every = '1.5m';
final intervalRule = interval.build().record!['rule'] as JsonMap;
expect(intervalRule['every'], '1.5m');
expect(intervalRule.containsKey('times'), isFalse);
expect(intervalRule['future'], 'keep');
});
test('the source record is never aliased by a built payload', () {
final original = completeRecord();
final schedule = SavedSchedule(original);
final first = (ScheduleDraft.fromSchedule(schedule)).build();
expect(first.record, isNotNull);
expect(schedule.toJson(), original);
final second = (ScheduleDraft.fromSchedule(
schedule,
)..prompt = 'Other').build();
expect((second.record!['input'] as JsonMap)['prompt'], 'Other');
expect(schedule.input['prompt'], 'Topic');
});
}
@@ -0,0 +1,130 @@
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 'draft_fixtures.dart';
void main() {
test('invalid intervals are field errors and never a record', () {
for (final every in [
'',
'59s',
'NaN',
'-1h',
'1.1x',
'Infinityh',
'1m2h x',
]) {
final draft =
ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv')
..name = 'Timer'
..prompt = 'Prompt'
..every = every;
final result = draft.build();
expect(result.record, isNull, reason: every);
expect(
result.errors['every'],
'Interval must be at least 1m (for example 24h or 1h30m).',
reason: every,
);
}
for (final every in ['1m', '.5h', '1h30m', '24h']) {
final draft =
ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv')
..name = 'Timer'
..prompt = 'Prompt'
..every = every;
final result = draft.build();
expect(result.record, isNotNull, reason: every);
expect((result.record!['rule'] as JsonMap)['every'], every);
}
});
test('invalid clock times, weekdays and timezones are field errors', () {
final draft =
ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv')
..name = 'Timer'
..prompt = 'Prompt'
..mode = ScheduleTimerMode.clock
..times = '24:00'
..days = ['mon', 'mon']
..timezone = 'Nowhere/Invalid'
..notifyMode = 'sometimes';
final result = draft.build();
expect(result.record, isNull);
expect(
result.errors['times'],
'Enter distinct 24-hour times, such as 09:00, 17:30.',
);
expect(result.errors['days'], 'Choose valid, distinct weekdays.');
expect(result.errors['timezone'], 'Enter a valid IANA timezone.');
expect(result.errors['notifyMode'], 'Choose a notification mode.');
for (final times in ['', '9:00', '09:60', '09:00,09:00']) {
final invalid =
ScheduleDraft.fromSchedule(SavedSchedule(completeRecord()))
..mode = ScheduleTimerMode.clock
..times = times;
expect(invalid.build().errors['times'], isNotNull, reason: times);
}
for (final timezone in ['Europe', 'Europe/', '/London']) {
final invalid =
ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv')
..name = 'Timer'
..prompt = 'Prompt'
..timezone = timezone;
expect(invalid.build().errors['timezone'], isNotNull, reason: timezone);
}
for (final timezone in ['Local', 'UTC', 'Asia/Tokyo', 'Etc/GMT+5']) {
final valid =
ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv')
..name = 'Timer'
..prompt = 'Prompt'
..timezone = timezone;
expect(valid.build().isValid, isTrue, reason: timezone);
}
});
test('invalid core fields report every error without mutating the draft', () {
final draft = ScheduleDraft.create(pipelineId: 4)
..prompt = ' '
..version = '7junk'
..workspace = '/srv\npath';
final before = {
'name': draft.name,
'prompt': draft.prompt,
'version': draft.version,
'workspace': draft.workspace,
};
final result = draft.build();
expect(result.record, isNull);
expect(result.errors, {
'name': 'Enter a schedule name.',
'prompt': 'Enter a prompt.',
'version': 'Choose a positive pinned version, not latest (0).',
'workspace': 'Enter an absolute workspace path on the server.',
});
expect({
'name': draft.name,
'prompt': draft.prompt,
'version': draft.version,
'workspace': draft.workspace,
}, before);
for (final version in ['0', '-1', '1.2', 'Infinity']) {
final invalid = ScheduleDraft.fromSchedule(
SavedSchedule(completeRecord()),
)..version = version;
expect(invalid.build().errors['version'], isNotNull, reason: version);
}
for (final workspace in ['', 'relative', '~/repo']) {
final invalid = ScheduleDraft.fromSchedule(
SavedSchedule(completeRecord()),
)..workspace = workspace;
expect(invalid.build().errors['workspace'], isNotNull, reason: workspace);
}
});
}