From ea2179cd663f5f029ea44673015cedf571fb9185 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 00:41:55 +0100 Subject: [PATCH] feat(app): wire saved schedules into the pipeline summary --- app/lib/features/pipelines/screen.dart | 7 +- .../widgets/pipeline_detail_panel.dart | 9 +- .../widgets/pipeline_summary_view.dart | 15 +- .../ui/editor/schedule_editor_form.dart | 6 + .../ui/editor/schedule_editor_form_body.dart | 8 +- .../ui/list/schedule_list_format.dart | 22 + .../ui/pipeline/schedule_delete_dialog.dart | 143 ++++++ .../schedule_pipeline_controller.dart | 101 +++++ .../ui/pipeline/schedule_pipeline_editor.dart | 93 ++++ .../pipeline/schedule_pipeline_list_body.dart | 152 +++++++ .../ui/pipeline/schedule_pipeline_row.dart | 114 +++++ .../pipeline/schedule_pipeline_section.dart | 165 +++++++ .../ui/pipeline/schedule_pipeline_styles.dart | 71 +++ .../pipeline/schedule_pipeline_wording.dart | 42 ++ app/notes/S1-wire.md | 188 ++++++++ .../pipeline_summary_schedules_test.dart | 84 ++++ .../pipelines/pipelines_adaptive_test.dart | 11 +- app/test/features/pipelines/test_helpers.dart | 1 + .../schedule_pipeline_section_test.dart | 402 +++++++++++++++++ .../schedule_pipeline_test_support.dart | 143 ++++++ app/tool/schedule_pipeline_probe.mjs | 407 ++++++++++++++++++ app/tool/schedule_pipeline_probe_app.dart | 208 +++++++++ 22 files changed, 2381 insertions(+), 11 deletions(-) create mode 100644 app/lib/features/schedules/ui/pipeline/schedule_delete_dialog.dart create mode 100644 app/lib/features/schedules/ui/pipeline/schedule_pipeline_controller.dart create mode 100644 app/lib/features/schedules/ui/pipeline/schedule_pipeline_editor.dart create mode 100644 app/lib/features/schedules/ui/pipeline/schedule_pipeline_list_body.dart create mode 100644 app/lib/features/schedules/ui/pipeline/schedule_pipeline_row.dart create mode 100644 app/lib/features/schedules/ui/pipeline/schedule_pipeline_section.dart create mode 100644 app/lib/features/schedules/ui/pipeline/schedule_pipeline_styles.dart create mode 100644 app/lib/features/schedules/ui/pipeline/schedule_pipeline_wording.dart create mode 100644 app/notes/S1-wire.md create mode 100644 app/test/features/pipelines/pipeline_summary_schedules_test.dart create mode 100644 app/test/features/schedules/ui/pipeline/schedule_pipeline_section_test.dart create mode 100644 app/test/features/schedules/ui/pipeline/schedule_pipeline_test_support.dart create mode 100644 app/tool/schedule_pipeline_probe.mjs create mode 100644 app/tool/schedule_pipeline_probe_app.dart diff --git a/app/lib/features/pipelines/screen.dart b/app/lib/features/pipelines/screen.dart index c0cc571b..092b9227 100644 --- a/app/lib/features/pipelines/screen.dart +++ b/app/lib/features/pipelines/screen.dart @@ -81,7 +81,11 @@ class _PipelinesScreenState extends State { final wide = constraints.maxWidth >= kPipelinesWideBreakpoint; if (!wide) { return _controller.hasSelection - ? PipelineDetailPanel(controller: _controller, showBack: true) + ? PipelineDetailPanel( + controller: _controller, + gateway: widget.gateway, + showBack: true, + ) : PipelineListPanel(controller: _controller); } return Row( @@ -96,6 +100,7 @@ class _PipelinesScreenState extends State { flex: 3, child: PipelineDetailPanel( controller: _controller, + gateway: widget.gateway, showBack: false, ), ), diff --git a/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart b/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart index fcf08fc4..be6636d2 100644 --- a/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart +++ b/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart @@ -2,6 +2,7 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; +import '../../../core/api_gateway.dart'; import '../../graph/widgets/stage_definition_view.dart'; import '../pipeline_models.dart'; import '../pipeline_query.dart'; @@ -25,10 +26,12 @@ class PipelineDetailPanel extends StatefulWidget { const PipelineDetailPanel({ super.key, required this.controller, + required this.gateway, required this.showBack, }); final PipelinesController controller; + final ApiGateway gateway; final bool showBack; @override @@ -94,7 +97,11 @@ class _PipelineDetailPanelState extends State { Expanded( child: switch (_tab) { PipelineDetailTab.summary => _scrolling( - PipelineSummaryView(controller: _controller, detail: detail), + PipelineSummaryView( + controller: _controller, + detail: detail, + gateway: widget.gateway, + ), ), PipelineDetailTab.graph => PipelineGraphTab( detail: detail, diff --git a/app/lib/features/pipelines/widgets/pipeline_summary_view.dart b/app/lib/features/pipelines/widgets/pipeline_summary_view.dart index 9266b268..ea78de0a 100644 --- a/app/lib/features/pipelines/widgets/pipeline_summary_view.dart +++ b/app/lib/features/pipelines/widgets/pipeline_summary_view.dart @@ -1,6 +1,8 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import '../../../core/api_gateway.dart'; +import '../../schedules/ui/pipeline/schedule_pipeline_section.dart'; import '../pipeline_format.dart'; import '../pipeline_models.dart'; import '../pipeline_query.dart'; @@ -8,18 +10,20 @@ import '../pipelines_controller.dart'; import 'pipeline_controls.dart'; import 'pipeline_detail_styles.dart'; -/// Summary tab: key/value facts plus the version history. Version rows are -/// selectable; the latest version's row is marked and a historical selection -/// offers an explicit return to latest. +/// Summary tab: key/value facts, the pipeline's saved schedules and the version +/// history. Version rows are selectable; the latest version's row is marked and +/// a historical selection offers an explicit return to latest. class PipelineSummaryView extends StatelessWidget { const PipelineSummaryView({ super.key, required this.controller, required this.detail, + required this.gateway, }); final PipelinesController controller; final PipelineDetail detail; + final ApiGateway gateway; @override Widget build(BuildContext context) { @@ -37,6 +41,11 @@ class PipelineSummaryView extends StatelessWidget { ), ), _fields(context), + SchedulePipelineSection( + gateway: gateway, + pipelineId: detail.id, + version: detail.resolvedVersion, + ), _versions(context), ], ); diff --git a/app/lib/features/schedules/ui/editor/schedule_editor_form.dart b/app/lib/features/schedules/ui/editor/schedule_editor_form.dart index 8862e3d6..4180544b 100644 --- a/app/lib/features/schedules/ui/editor/schedule_editor_form.dart +++ b/app/lib/features/schedules/ui/editor/schedule_editor_form.dart @@ -28,6 +28,7 @@ class ScheduleEditorForm extends StatefulWidget { required this.onSubmit, this.onCancel, this.title, + this.showHeading = true, }); final ScheduleDraft draft; @@ -35,6 +36,10 @@ class ScheduleEditorForm extends StatefulWidget { final VoidCallback? onCancel; final String? title; + /// False when the hosting native page already shows the add/edit title in its + /// navigation bar, so the form does not repeat it. + final bool showHeading; + @override State createState() => _ScheduleEditorFormState(); } @@ -149,6 +154,7 @@ class _ScheduleEditorFormState extends State { final cupertino = usesCupertinoHost(context); return ScheduleEditorFormBody( heading: _heading, + showHeading: widget.showHeading, name: _name, prompt: _prompt, version: _version, diff --git a/app/lib/features/schedules/ui/editor/schedule_editor_form_body.dart b/app/lib/features/schedules/ui/editor/schedule_editor_form_body.dart index 5b4a2f19..23059c40 100644 --- a/app/lib/features/schedules/ui/editor/schedule_editor_form_body.dart +++ b/app/lib/features/schedules/ui/editor/schedule_editor_form_body.dart @@ -14,6 +14,7 @@ class ScheduleEditorFormBody extends StatelessWidget { const ScheduleEditorFormBody({ super.key, required this.heading, + this.showHeading = true, required this.name, required this.prompt, required this.version, @@ -37,6 +38,7 @@ class ScheduleEditorFormBody extends StatelessWidget { }); final String heading; + final bool showHeading; final TextEditingController name; final TextEditingController prompt; final TextEditingController version; @@ -106,8 +108,10 @@ class ScheduleEditorFormBody extends StatelessWidget { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Text(heading, style: titleStyle), - const SizedBox(height: 8), + if (showHeading) ...[ + Text(heading, style: titleStyle), + const SizedBox(height: 8), + ], Text(scheduleEditorNote, style: scheduleEditorSecondaryStyle(context)), _gap, _textField( diff --git a/app/lib/features/schedules/ui/list/schedule_list_format.dart b/app/lib/features/schedules/ui/list/schedule_list_format.dart index 308e0eb5..46990bf2 100644 --- a/app/lib/features/schedules/ui/list/schedule_list_format.dart +++ b/app/lib/features/schedules/ui/list/schedule_list_format.dart @@ -39,6 +39,28 @@ String scheduleTimerValue(SavedSchedule schedule) { return rule.days.isEmpty ? repeat : '$repeat · ${rule.days.join(', ')}'; } +/// The web's `scheduleRuleLabel`, used by the pipeline Summary: timer words, +/// weekdays and the effective timezone in one line. A rule without an interval +/// or clock times is reported as unavailable instead of showing only a zone. +String scheduleRuleSummary(SavedSchedule schedule) { + final rule = schedule.rule; + final repeat = rule.every.isNotEmpty + ? 'Every ${rule.every}' + : rule.times.isNotEmpty + ? rule.times.join(', ') + : ''; + if (repeat.isEmpty) return 'Timer unavailable'; + return [ + repeat, + if (rule.days.isNotEmpty) rule.days.join(', '), + scheduleTimezoneValue(schedule), + ].join(' · '); +} + +/// The pinned version on its own, for a section already scoped to one pipeline. +String schedulePinnedVersionValue(SavedSchedule schedule) => + schedule.version == null ? 'Version unavailable' : 'v${schedule.version}'; + /// Matches the web client: an empty or `Local` rule timezone means the server /// applies its own timezone, which is not an absent value. String scheduleTimezoneValue(SavedSchedule schedule) { diff --git a/app/lib/features/schedules/ui/pipeline/schedule_delete_dialog.dart b/app/lib/features/schedules/ui/pipeline/schedule_delete_dialog.dart new file mode 100644 index 00000000..0a6f1caf --- /dev/null +++ b/app/lib/features/schedules/ui/pipeline/schedule_delete_dialog.dart @@ -0,0 +1,143 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../ui/adaptive/host.dart'; +import 'schedule_pipeline_wording.dart'; + +/// Deletes the exact schedule revision. Returns null once the server accepted +/// the delete, or the server's own reasons verbatim. +typedef ScheduleDeleteSubmit = Future Function(); + +/// Opens the one native confirmation for a schedule deletion. +/// +/// Nothing is sent until `Delete schedule` is pressed; `Keep schedule` only +/// closes the prompt. A refusal keeps the prompt open with the server's words. +Future showScheduleDeleteDialog({ + required BuildContext context, + required String name, + required ScheduleDeleteSubmit onSubmit, +}) { + final prompt = _ScheduleDeletePrompt(name: name, onSubmit: onSubmit); + if (usesCupertinoHost(context)) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _ScheduleDeletePrompt extends StatefulWidget { + const _ScheduleDeletePrompt({required this.name, required this.onSubmit}); + + final String name; + final ScheduleDeleteSubmit onSubmit; + + @override + State<_ScheduleDeletePrompt> createState() => _ScheduleDeletePromptState(); +} + +class _ScheduleDeletePromptState extends State<_ScheduleDeletePrompt> { + bool _sending = false; + String? _refusal; + + void _keep() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _confirm() async { + if (_sending) return; + setState(() { + _sending = true; + _refusal = null; + }); + final refusal = await widget.onSubmit(); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + setState(() { + _sending = false; + _refusal = refusal; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = usesCupertinoHost(context) + ? _cupertino(context) + : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + Widget _material(BuildContext context) { + return AlertDialog( + scrollable: true, + title: Text(scheduleDeleteTitle(widget.name)), + content: _body( + errorStyle: TextStyle(color: Theme.of(context).colorScheme.error), + ), + actions: [ + TextButton( + key: scheduleDeleteKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(scheduleDeleteKeepLabel), + ), + FilledButton( + key: scheduleDeleteConfirmKey, + onPressed: _sending ? null : _confirm, + child: const Text(scheduleDeleteConfirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: Text(scheduleDeleteTitle(widget.name)), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + CupertinoDialogAction( + key: scheduleDeleteKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(scheduleDeleteKeepLabel), + ), + CupertinoDialogAction( + key: scheduleDeleteConfirmKey, + isDestructiveAction: true, + onPressed: _sending ? null : _confirm, + child: const Text(scheduleDeleteConfirmLabel), + ), + ], + ); + } + + Widget _body({required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text(scheduleDeleteMessage), + if (_refusal case final refusal?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + refusal, + key: scheduleDeleteErrorKey, + style: errorStyle, + ), + ), + ], + ); + } +} diff --git a/app/lib/features/schedules/ui/pipeline/schedule_pipeline_controller.dart b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_controller.dart new file mode 100644 index 00000000..8e9d8488 --- /dev/null +++ b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_controller.dart @@ -0,0 +1,101 @@ +import 'package:flutter/foundation.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../data/schedules_repository.dart'; +import '../../domain/saved_schedule.dart'; +import '../list/schedule_list_controller.dart'; + +/// The message to show for a failed save/delete/pause, using the repository's +/// older-server guidance when the reply itself is unsupported. +String scheduleActionError(Object error) => + ScheduleListFailure.from(error).message; + +/// Saved schedules for exactly one pipeline, with the two mutations the +/// pipeline Summary offers. +/// +/// Every accepted save/delete is followed by `list_schedules`; the section never +/// invents, edits or reorders a row locally. Saving does not start a run and +/// nothing here publishes, validates or runs a workflow. +class SchedulePipelineController extends ChangeNotifier { + SchedulePipelineController({ + required this.repository, + required this.pipelineId, + }); + + final SchedulesRepository repository; + final int pipelineId; + + List _schedules = const []; + bool _loading = false; + bool _loaded = false; + ScheduleListFailure? _failure; + int _generation = 0; + bool _disposed = false; + + List get schedules => _schedules; + bool get isLoading => _loading; + bool get hasLoaded => _loaded; + bool get isInitialLoading => _loading && !_loaded; + ScheduleListFailure? get failure => _failure; + + /// Re-reads server truth. A failed refresh keeps the rows already loaded so a + /// refused mutation never silently empties the section. + Future refresh() async { + final generation = ++_generation; + _loading = true; + _failure = null; + _notify(); + try { + final rows = await repository.listSchedules(pipelineId: pipelineId); + if (!_owns(generation)) return; + _schedules = List.unmodifiable(rows); + _loaded = true; + } catch (error) { + if (!_owns(generation)) return; + _failure = ScheduleListFailure.from(error); + } finally { + if (_owns(generation)) { + _loading = false; + _notify(); + } + } + } + + /// Creates (with a stable create key) or updates from the editor's exact + /// record. A server refusal is propagated unchanged; a later refresh failure + /// is reported separately and does not pretend the accepted save failed. + Future saveRecord(JsonMap record, {String? requestKey}) async { + await repository.saveSchedule(record, requestKey: requestKey); + await refresh(); + } + + /// Reuses the exact loaded record, changing only `enabled`. Identity, + /// revision and unknown fields stay in the payload. + Future setEnabled(SavedSchedule schedule) => + saveRecord(schedule.withEnabled(!schedule.enabled).toJson()); + + /// Sends the exact identity and compare-and-swap revision of the loaded row. + Future delete(SavedSchedule schedule) async { + final id = schedule.id; + final revision = schedule.revision; + if (id == null || revision == null) { + throw const SchedulesRepositoryException( + 'An exact schedule ID and revision are required.', + ); + } + await repository.deleteSchedule(id, revision); + await refresh(); + } + + bool _owns(int generation) => !_disposed && generation == _generation; + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } +} diff --git a/app/lib/features/schedules/ui/pipeline/schedule_pipeline_editor.dart b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_editor.dart new file mode 100644 index 00000000..2788b844 --- /dev/null +++ b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_editor.dart @@ -0,0 +1,93 @@ +import 'dart:math'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../../../ui/adaptive/host.dart'; +import '../../domain/editor/schedule_draft.dart'; +import '../editor/schedule_editor_form.dart'; +import '../editor/schedule_editor_wording.dart'; + +/// A create request key minted once when the editor is opened for a new +/// schedule. Retrying that same editor reuses it, so a lost reply cannot create +/// a duplicate; a new Add opens a new key. +String newScheduleCreateRequestKey() { + final now = DateTime.now().microsecondsSinceEpoch.toRadixString(36); + // `1 << 32` is 0 under the web's 32-bit shifts, so keep the range below that. + final random = Random().nextInt(1 << 30).toRadixString(36); + return 'schedule:flutter-$now-$random'; +} + +/// Opens the landed [ScheduleEditorForm] as a native full-screen page. +/// +/// The page supplies only the route and its standard back/title chrome; the +/// form validates and builds the exact record. [onSubmit] is the save callback: +/// it throwing a server refusal keeps this page open with every typed value, +/// and returning accepted truth closes it. +Future openSchedulePipelineEditor( + BuildContext context, { + required ScheduleDraft draft, + required Future Function(JsonMap record) onSubmit, +}) { + final page = _SchedulePipelineEditorPage(draft: draft, onSubmit: onSubmit); + final settings = RouteSettings( + name: draft.source == null + ? 'schedule/new/${draft.pipelineId ?? 0}' + : 'schedule/${draft.source?.id ?? 0}', + ); + final title = draft.source == null + ? scheduleEditorAddTitle + : scheduleEditorEditTitle; + final route = usesCupertinoHost(context) + ? CupertinoPageRoute( + settings: settings, + builder: (_) => CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar(middle: Text(title)), + child: SafeArea(top: false, child: page), + ), + ) + : MaterialPageRoute( + settings: settings, + builder: (_) => Scaffold( + appBar: AppBar(title: Text(title)), + body: SafeArea(child: page), + ), + ); + return Navigator.of(context).push(route); +} + +class _SchedulePipelineEditorPage extends StatefulWidget { + const _SchedulePipelineEditorPage({ + required this.draft, + required this.onSubmit, + }); + + final ScheduleDraft draft; + final Future Function(JsonMap record) onSubmit; + + @override + State<_SchedulePipelineEditorPage> createState() => + _SchedulePipelineEditorPageState(); +} + +class _SchedulePipelineEditorPageState + extends State<_SchedulePipelineEditorPage> { + Future _submit(JsonMap record) async { + await widget.onSubmit(record); + if (mounted) Navigator.of(context).pop(); + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: ScheduleEditorForm( + draft: widget.draft, + showHeading: false, + onSubmit: _submit, + onCancel: () => Navigator.of(context).pop(), + ), + ); + } +} diff --git a/app/lib/features/schedules/ui/pipeline/schedule_pipeline_list_body.dart b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_list_body.dart new file mode 100644 index 00000000..40c8361f --- /dev/null +++ b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_list_body.dart @@ -0,0 +1,152 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../domain/saved_schedule.dart'; +import '../list/schedule_list_controller.dart'; +import 'schedule_pipeline_controller.dart'; +import 'schedule_pipeline_row.dart'; +import 'schedule_pipeline_styles.dart'; +import 'schedule_pipeline_wording.dart'; + +/// The visible schedule list of the pipeline Summary. State and mutations stay +/// in `SchedulePipelineSection`; this widget renders one frame of them. +class SchedulePipelineListBody extends StatelessWidget { + const SchedulePipelineListBody({ + super.key, + required this.controller, + required this.busyRows, + required this.rowErrors, + required this.onAdd, + required this.onEdit, + required this.onToggle, + required this.onDelete, + }); + + final SchedulePipelineController controller; + final Set busyRows; + final Map rowErrors; + final VoidCallback onAdd; + final ValueChanged onEdit; + final ValueChanged onToggle; + final ValueChanged onDelete; + + @override + Widget build(BuildContext context) { + final failure = controller.failure; + final schedules = controller.schedules; + return Padding( + key: scheduleSectionKey, + padding: const EdgeInsets.only(bottom: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 4), + child: _header(context), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + scheduleSectionNote, + style: schedulePipelineMutedStyle(context), + ), + ), + if (controller.isInitialLoading) + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + child: Semantics( + liveRegion: true, + label: scheduleSectionLoading, + child: Text( + scheduleSectionLoading, + style: schedulePipelineMutedStyle(context), + ), + ), + ), + if (failure != null) + _failure(context, failure) + else if (controller.hasLoaded && schedules.isEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + child: Text( + scheduleSectionEmpty, + style: schedulePipelineMutedStyle(context), + ), + ), + for (var index = 0; index < schedules.length; index++) ...[ + _row(context, schedules[index]), + if (index < schedules.length - 1) + schedulePipelineSeparator(context), + ], + ], + ), + ); + } + + Widget _header(BuildContext context) { + return Wrap( + spacing: 12, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Semantics( + header: true, + container: true, + child: Text( + controller.hasLoaded && controller.failure == null + ? '$scheduleSectionTitle (${controller.schedules.length})' + : scheduleSectionTitle, + style: schedulePipelineHeadingStyle(context), + ), + ), + schedulePipelineTextButton( + context, + key: scheduleRefreshKey, + label: scheduleRefreshLabel, + onPressed: controller.isLoading ? null : controller.refresh, + ), + schedulePipelineTextButton( + context, + key: scheduleAddKey, + label: scheduleAddLabel, + onPressed: onAdd, + ), + ], + ); + } + + Widget _row(BuildContext context, SavedSchedule schedule) { + final id = schedule.id; + return SchedulePipelineRow( + schedule: schedule, + busy: id != null && busyRows.contains(id), + error: id == null ? null : rowErrors[id], + onEdit: () => onEdit(schedule), + onToggle: () => onToggle(schedule), + onDelete: () => onDelete(schedule), + ); + } + + Widget _failure(BuildContext context, ScheduleListFailure failure) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Semantics( + liveRegion: true, + child: Text( + failure.message, + style: schedulePipelineErrorStyle(context), + ), + ), + schedulePipelineTextButton( + context, + label: 'Retry', + onPressed: controller.isLoading ? null : controller.refresh, + ), + ], + ), + ); + } +} diff --git a/app/lib/features/schedules/ui/pipeline/schedule_pipeline_row.dart b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_row.dart new file mode 100644 index 00000000..8d6ae20a --- /dev/null +++ b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_row.dart @@ -0,0 +1,114 @@ +import 'package:flutter/material.dart'; + +import '../../domain/saved_schedule.dart'; +import '../list/schedule_list_format.dart'; +import 'schedule_pipeline_styles.dart'; +import 'schedule_pipeline_wording.dart'; + +/// One saved schedule in the pipeline Summary: name, state, pinned version and +/// timer words, the recorded due time, and its Edit/Pause-Enable/Delete actions. +class SchedulePipelineRow extends StatelessWidget { + const SchedulePipelineRow({ + super.key, + required this.schedule, + required this.busy, + required this.onEdit, + required this.onToggle, + required this.onDelete, + this.error, + }); + + final SavedSchedule schedule; + final bool busy; + final String? error; + final VoidCallback onEdit; + final VoidCallback onToggle; + final VoidCallback onDelete; + + @override + Widget build(BuildContext context) { + final id = schedule.id; + return Padding( + key: scheduleRowKey(id), + padding: const EdgeInsets.fromLTRB(16, 12, 16, 12), + child: Semantics( + container: true, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Text( + scheduleDisplayName(schedule), + style: schedulePipelineBodyStyle(context), + ), + ), + const SizedBox(width: 8), + Text( + scheduleStatusLabel(schedule), + style: schedulePipelineStatusStyle(context, schedule.enabled), + ), + ], + ), + const SizedBox(height: 4), + Text( + 'Pinned ${schedulePinnedVersionValue(schedule)} · ' + '${scheduleRuleSummary(schedule)}', + style: schedulePipelineMutedStyle(context), + ), + if (schedule.prompt.isNotEmpty) ...[ + const SizedBox(height: 4), + Text(schedule.prompt, style: schedulePipelineBodyStyle(context)), + ], + const SizedBox(height: 4), + Text( + '$scheduleNextPrefix${scheduleNextDueValue(schedule)}', + style: schedulePipelineMutedStyle(context), + ), + const SizedBox(height: 4), + Wrap( + spacing: 8, + runSpacing: 4, + children: [ + schedulePipelineTextButton( + context, + key: scheduleRowEditKey(id), + label: scheduleEditLabel, + onPressed: busy ? null : onEdit, + ), + schedulePipelineTextButton( + context, + key: scheduleRowToggleKey(id), + label: schedule.enabled + ? schedulePauseLabel + : scheduleEnableLabel, + onPressed: busy ? null : onToggle, + ), + schedulePipelineTextButton( + context, + key: scheduleRowDeleteKey(id), + label: scheduleDeleteLabel, + onPressed: busy ? null : onDelete, + ), + ], + ), + if (error case final text?) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Semantics( + liveRegion: true, + child: Text( + text, + key: scheduleRowErrorKey(id), + style: schedulePipelineErrorStyle(context), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/features/schedules/ui/pipeline/schedule_pipeline_section.dart b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_section.dart new file mode 100644 index 00000000..f9b7b254 --- /dev/null +++ b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_section.dart @@ -0,0 +1,165 @@ +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../../settings/settings_store.dart'; +import '../../data/schedules_repository.dart'; +import '../../domain/editor/schedule_draft.dart'; +import '../../domain/saved_schedule.dart'; +import '../list/schedule_list_format.dart'; +import 'schedule_delete_dialog.dart'; +import 'schedule_pipeline_controller.dart'; +import 'schedule_pipeline_editor.dart'; +import 'schedule_pipeline_list_body.dart'; + +/// The pipeline Summary's Schedules section. +/// +/// Lists exactly this pipeline's saved run configurations and offers Add, +/// Edit, Pause/Enable and Delete. Every accepted mutation re-reads +/// `list_schedules`; nothing is updated optimistically. This section never +/// publishes, validates or runs a workflow and never starts a run. +class SchedulePipelineSection extends StatefulWidget { + const SchedulePipelineSection({ + super.key, + required this.gateway, + required this.pipelineId, + required this.version, + this.settingsStore = const SharedPreferencesSettingsStore(), + }); + + final ApiGateway gateway; + final int pipelineId; + + /// The resolved version currently shown, used as a new schedule's pin. + final int version; + + /// The operator's persisted server workspace seeds a new schedule's absolute + /// workspace, matching the web client's configured workspace. + final SettingsStore settingsStore; + + @override + State createState() => + _SchedulePipelineSectionState(); +} + +class _SchedulePipelineSectionState extends State { + late SchedulePipelineController _controller; + final Map _rowErrors = {}; + final Set _busyRows = {}; + Future? _settings; + + @override + void initState() { + super.initState(); + _controller = _createController()..refresh(); + } + + SchedulePipelineController _createController() => SchedulePipelineController( + repository: SchedulesRepository(widget.gateway), + pipelineId: widget.pipelineId, + ); + + @override + void didUpdateWidget(SchedulePipelineSection oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.gateway != widget.gateway || + oldWidget.pipelineId != widget.pipelineId) { + _controller.dispose(); + _controller = _createController()..refresh(); + _rowErrors.clear(); + _busyRows.clear(); + } + if (oldWidget.settingsStore != widget.settingsStore) _settings = null; + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Future _workspace() async { + final settings = _settings ??= widget.settingsStore.load(); + try { + return (await settings).workspace.trim(); + } catch (_) { + return ''; + } + } + + Future _add() async { + final workspace = await _workspace(); + if (!mounted) return; + final requestKey = newScheduleCreateRequestKey(); + final draft = ScheduleDraft.create( + pipelineId: widget.pipelineId, + version: '${widget.version}', + workspace: workspace, + ); + await openSchedulePipelineEditor( + context, + draft: draft, + onSubmit: (record) async { + await _controller.saveRecord(record, requestKey: requestKey); + }, + ); + } + + Future _edit(SavedSchedule schedule) { + return openSchedulePipelineEditor( + context, + draft: ScheduleDraft.fromSchedule(schedule), + onSubmit: (record) async { + await _controller.saveRecord(record); + }, + ); + } + + Future _toggle(SavedSchedule schedule) async { + final id = schedule.id; + if (id == null) return; + setState(() { + _busyRows.add(id); + _rowErrors.remove(id); + }); + try { + await _controller.setEnabled(schedule); + } catch (error) { + if (mounted) { + setState(() => _rowErrors[id] = scheduleActionError(error)); + } + } finally { + if (mounted) setState(() => _busyRows.remove(id)); + } + } + + Future _delete(SavedSchedule schedule) { + return showScheduleDeleteDialog( + context: context, + name: scheduleDisplayName(schedule), + onSubmit: () async { + try { + await _controller.delete(schedule); + return null; + } catch (error) { + return scheduleActionError(error); + } + }, + ); + } + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: _controller, + builder: (context, _) => SchedulePipelineListBody( + controller: _controller, + busyRows: _busyRows, + rowErrors: _rowErrors, + onAdd: _add, + onEdit: _edit, + onToggle: _toggle, + onDelete: _delete, + ), + ); + } +} diff --git a/app/lib/features/schedules/ui/pipeline/schedule_pipeline_styles.dart b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_styles.dart new file mode 100644 index 00000000..048cfdbd --- /dev/null +++ b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_styles.dart @@ -0,0 +1,71 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../ui/adaptive/host.dart'; + +/// Host text roles and standard buttons for the pipeline schedule section. +/// No palette, font family or explicit point size is introduced. +TextStyle? schedulePipelineHeadingStyle(BuildContext context) => + usesCupertinoHost(context) + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleMedium; + +TextStyle? schedulePipelineBodyStyle(BuildContext context) => + usesCupertinoHost(context) + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodyLarge; + +TextStyle? schedulePipelineMutedStyle(BuildContext context) { + if (usesCupertinoHost(context)) { + return CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith( + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ); + } + final theme = Theme.of(context); + return theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ); +} + +TextStyle? schedulePipelineStatusStyle(BuildContext context, bool enabled) { + final base = schedulePipelineMutedStyle(context); + if (!enabled) return base; + return usesCupertinoHost(context) + ? base?.copyWith(color: CupertinoTheme.of(context).primaryColor) + : base?.copyWith(color: Theme.of(context).colorScheme.primary); +} + +TextStyle? schedulePipelineErrorStyle(BuildContext context) => + usesCupertinoHost(context) + ? CupertinoTheme.of(context).textTheme.textStyle.copyWith( + color: CupertinoColors.systemRed.resolveFrom(context), + ) + : TextStyle(color: Theme.of(context).colorScheme.error); + +/// A standard platform text action. +Widget schedulePipelineTextButton( + BuildContext context, { + required String label, + required VoidCallback? onPressed, + Key? key, +}) { + if (usesCupertinoHost(context)) { + return CupertinoButton( + key: key, + padding: EdgeInsets.zero, + onPressed: onPressed, + child: Text(label), + ); + } + return TextButton(key: key, onPressed: onPressed, child: Text(label)); +} + +Widget schedulePipelineSeparator(BuildContext context) { + if (usesCupertinoHost(context)) { + return Container( + height: 1 / MediaQuery.devicePixelRatioOf(context), + color: CupertinoColors.separator.resolveFrom(context), + ); + } + return const Divider(height: 1); +} diff --git a/app/lib/features/schedules/ui/pipeline/schedule_pipeline_wording.dart b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_wording.dart new file mode 100644 index 00000000..d1c5c022 --- /dev/null +++ b/app/lib/features/schedules/ui/pipeline/schedule_pipeline_wording.dart @@ -0,0 +1,42 @@ +import 'package:flutter/widgets.dart'; + +/// Browser wording and stable keys for the pipeline Summary schedule section, +/// kept verbatim from `web/src/views/schedules.js`. +const scheduleSectionTitle = 'Schedules'; +const scheduleSectionNote = + 'Independent prompts and timers for this pipeline. Schedules do not ' + 'change its definition.'; +const scheduleSectionEmpty = + 'No schedules yet. Add one for each topic or recurring task.'; +const scheduleSectionLoading = 'Loading schedules…'; +const scheduleAddLabel = 'Add schedule'; +const scheduleRefreshLabel = 'Refresh'; +const scheduleEditLabel = 'Edit'; +const schedulePauseLabel = 'Pause'; +const scheduleEnableLabel = 'Enable'; +const scheduleDeleteLabel = 'Delete'; +const scheduleDeleteKeepLabel = 'Keep schedule'; +const scheduleDeleteConfirmLabel = 'Delete schedule'; +const scheduleDeleteMessage = + 'Future runs only. Run history and active runs will not be deleted.'; +const scheduleNextPrefix = 'Next: '; + +String scheduleDeleteTitle(String name) => 'Delete $name?'; + +const scheduleSectionKey = ValueKey('schedule-pipeline-section'); +const scheduleAddKey = ValueKey('schedule-pipeline-add'); +const scheduleRefreshKey = ValueKey('schedule-pipeline-refresh'); +const scheduleDeleteKeepKey = ValueKey('schedule-delete-keep'); +const scheduleDeleteConfirmKey = ValueKey('schedule-delete-confirm'); +const scheduleDeleteErrorKey = ValueKey('schedule-delete-error'); + +ValueKey scheduleRowKey(int? id) => + ValueKey('schedule-pipeline-row-${id ?? 'unknown'}'); +ValueKey scheduleRowEditKey(int? id) => + ValueKey('schedule-pipeline-edit-${id ?? 'unknown'}'); +ValueKey scheduleRowToggleKey(int? id) => + ValueKey('schedule-pipeline-toggle-${id ?? 'unknown'}'); +ValueKey scheduleRowDeleteKey(int? id) => + ValueKey('schedule-pipeline-delete-${id ?? 'unknown'}'); +ValueKey scheduleRowErrorKey(int? id) => + ValueKey('schedule-pipeline-error-${id ?? 'unknown'}'); diff --git a/app/notes/S1-wire.md b/app/notes/S1-wire.md new file mode 100644 index 00000000..325edb5c --- /dev/null +++ b/app/notes/S1-wire.md @@ -0,0 +1,188 @@ +# S1-wire — pipeline Summary schedules + +## Result + +The pipeline Summary now carries a native Schedules section for the selected +pipeline. It lists the server's saved schedules and wires the landed draft/form +to `SchedulesRepository`: create, edit, pause/enable and confirmed delete. Every +accepted mutation re-reads `list_schedules`; a refused mutation stays visible +with the server's own words. No workflow is published, validated or run and no +run is started. + +Candidate commit: the tip of `flutter/schedule-wire` (see `git log -1`). Not +merged, not pushed, not deployed. + +## Changed paths + +New source (all under `lib/features/schedules/ui/pipeline/`): + +| File | Lines | Responsibility | +| --- | ---: | --- | +| `schedule_pipeline_section.dart` | 165 | state/actions: list ownership, create/edit drafts, pause, delete, workspace seed | +| `schedule_pipeline_list_body.dart` | 152 | one frame of the visible section: heading/count, note, loading/empty/failure, rows | +| `schedule_pipeline_row.dart` | 114 | one schedule row: name, state, pinned version + timer words, due, actions, row refusal | +| `schedule_pipeline_controller.dart` | 101 | `list_schedules`, save + refresh, enabled-only update, exact delete | +| `schedule_pipeline_editor.dart` | 93 | native full-screen form route, create request key, close-on-accepted | +| `schedule_delete_dialog.dart` | 143 | one native delete confirmation with a refusal slot | +| `schedule_pipeline_styles.dart` | 71 | host text roles, standard text buttons, separators | +| `schedule_pipeline_wording.dart` | 42 | browser words and stable keys | + +Modified app files: + +- `lib/features/pipelines/widgets/pipeline_summary_view.dart` — inserts the + section between the facts and Versions; takes the gateway. +- `lib/features/pipelines/widgets/pipeline_detail_panel.dart` — passes the + gateway through to Summary. +- `lib/features/pipelines/screen.dart` — supplies its existing gateway. +- `lib/features/schedules/ui/editor/schedule_editor_form.dart` and + `..._form_body.dart` — optional `showHeading` (default true) so the hosting + page's navigation bar is the single title. +- `lib/features/schedules/ui/list/schedule_list_format.dart` — adds the web's + one-line rule summary and the pinned-version value. + +Tests and fixture: + +- `test/features/schedules/ui/pipeline/schedule_pipeline_section_test.dart` (402) +- `test/features/schedules/ui/pipeline/schedule_pipeline_test_support.dart` (143) +- `test/features/pipelines/pipeline_summary_schedules_test.dart` (84) +- `test/features/pipelines/test_helpers.dart` — the pipeline fixture now answers + `list_schedules` with an explicit empty list. +- `test/features/pipelines/pipelines_adaptive_test.dart` — supplies the gateway + to the directly constructed detail panel. +- `tool/schedule_pipeline_probe_app.dart` (208) and + `tool/schedule_pipeline_probe.mjs` (407) — isolated in-memory fixture and real + Chrome interaction. + +## Behavior and request shapes + +- **List**: `list_schedules` with `{pipeline_id: }`. A failed refresh + keeps the rows already shown and adds the failure line; an explicit empty reply + is `Schedules (0)` and `No schedules yet. Add one for each topic or recurring + task.` An unsupported/older reply reuses the existing upgrade guidance. +- **Create**: `Add schedule` opens the landed form over + `ScheduleDraft.create(pipelineId, version: detail.resolvedVersion, + workspace: )`. The key is minted once when the + editor opens and reused by every retry in that editor. The exact create record + sends `id: 0`, the pinned resolved version, absolute workspace, and + `request_key`; a second Add gets a new key. +- **Edit**: `Edit` starts from the exact `SavedSchedule` loaded from the server. + The form's landed draft/guard preserves `id`, `revision`, unknown record, + input, rule and run-option fields. No `request_key` is sent, matching web. +- **Save outcome**: only `save_schedule` is called. An accepted save is followed + by `list_schedules`; the row is never written locally first. A server refusal + (including a stale revision) keeps the editor open, every typed value intact, + and shows `" Your draft is preserved. …"`. +- **Pause/Enable**: sends the exact loaded record with only `enabled` toggled, + keeping identity, revision and every unknown field. No create key. +- **Delete**: one native confirmation (`Delete ?`, future runs only). + `Keep schedule` sends nothing; `Delete schedule` sends + `delete_schedule {schedule_id, expected_revision}` from the loaded row, then + refreshes. A refusal stays in the prompt; a later refresh failure is reported + separately. +- No `run_pipeline`, `validate`, `submit` or publish request exists in this + slice. Graph, Source, filters and the existing pipeline actions are untouched + except for passing the gateway through. + +## Verification actually run + +``` +dart format lib/features/schedules/ui/pipeline lib/features/schedules/ui/editor \ + lib/features/schedules/ui/list/schedule_list_format.dart \ + lib/features/pipelines lib/features/pipelines/widgets \ + test/features/schedules/ui/pipeline test/features/pipelines \ + tool/schedule_pipeline_probe_app.dart # clean +flutter analyze # No issues found! +flutter test test/features/schedules test/features/pipelines # 141 passed +flutter test # 956 passed +flutter build web # ✓ Built build/web +flutter build web -t tool/schedule_pipeline_probe_app.dart \ + -o build/schedule_pipeline_probe_web # ✓ Built +node --check tool/schedule_pipeline_probe.mjs # clean +OPENCODE_ARTIFACT_DIR=…/93/public/s1-wire-captures \ + PROBE_WEB_ROOT=build/schedule_pipeline_probe_web \ + node tool/schedule_pipeline_probe.mjs # 15 checks passed +git diff --check # clean +``` + +Widget coverage includes: exact create record with one key and pinned version; +edit preserving revision/unknown fields; conflict keeping the draft and server +words; pause changing only `enabled`; delete confirmation sending id + revision; +server-truth refresh after save; list/pause/delete refusals; 320px/2x Material +and dark Cupertino. The integration test opens the real `PipelinesScreen` and +checks the section plus a Source/Graph/Summary round trip. + +## Browser evidence + +Real headless Chrome against the isolated in-memory fixture, no Pipelines server +or authentication. Both native hosts ran list → new → invalid fields → valid +save → list refresh → conflict → accepted retry → pause → delete: + +- Material 390×844: list, editor, invalid errors, created refresh, conflict. +- Cupertino dark 390×844: the same flow and captures. +- Material 320×844 at 2x text: list and editor top/bottom. + +Captured facts include the create record +`{id:0, name:"Probe schedule", pipeline_id:4, version:3, enabled:true, +input:{prompt:"Summarise the release notes."}, workspace:"/srv/research", +rule:{every:"24h"}, notify_mode:"auto"}`, a non-empty stable request key, the +stale-revision conflict text with the typed name retained, a pause payload whose +only change is `enabled:false` at the loaded revision, and +`delete_schedule {schedule_id:8, expected_revision:5}`. + +Captures and manifest: + +``` +/Users/alan/.local/share/pipelines/data/artifacts/93/public/s1-wire-captures/ + s1w-material-390-list.png + s1w-material-390-editor.png + s1w-material-390-invalid.png + s1w-material-390-created.png + s1w-material-390-conflict.png + s1w-cupertino-dark-390-list.png + s1w-cupertino-dark-390-editor.png + s1w-cupertino-dark-390-invalid.png + s1w-cupertino-dark-390-created.png + s1w-cupertino-dark-390-conflict.png + s1w-material-320-2x-list.png + s1w-material-320-2x-editor-top.png + s1w-material-320-2x-editor-bottom.png + manifest.json +``` + +Inspected: Material list/invalid/created/conflict, Cupertino dark +list/editor/invalid/conflict, and both 320/2x captures. The list shows names, +`Enabled`/`Paused`, pinned version, timer words and due; the invalid capture +shows both field errors and the prefilled `3`/`/srv/research`; the conflict +capture shows the server reason and preservation copy in the host's error colour. + +The fixture caught a real web defect: `Random().nextInt(1 << 32)` throws on the +web because JS shifts are 32-bit, so the key range is now `1 << 30`. This was +only visible in the browser run, not in VM widget tests. + +## Full diff + +The complete candidate patch is at +`/Users/alan/.local/share/pipelines/data/artifacts/93/public/s1-wire.diff` +(`git show` of the candidate commit). + +## Honest limits + +- **Source candidate, not merged/pushed/deployed.** No main merge, canonical URL + change or service restart. +- **No live authenticated schedule mutation.** All mutation evidence is the + isolated fixture; no real operator schedule was created, paused or deleted. +- **Mobile unverified.** Only web-targeted Flutter tests, analysis and build ran. + No Android/iOS build, emulator, ADB or device was used. +- **Advanced run options are preserved but not editable** in the landed form + (`model`, stage models, other input keys, write paths, allow tools, title, + output format). Edit keeps them because the draft starts from the exact record. +- **Create seeds the persisted server workspace when one exists**, matching the + web's configured workspace; when the preference is empty the form requires the + operator to enter an absolute path. Create timezone stays blank (server + timezone), rather than guessing an IANA zone from the browser. +- **No separate Schedules route entry.** This slice is the pipeline Summary + section; shell/navigation entry and "Schedule this run" seeding remain + separate items. +- **Schedule count provenance on the pipeline list is unchanged.** The section + does not update the list's `schedule_count`; it refreshes only its own + `list_schedules` rows. diff --git a/app/test/features/pipelines/pipeline_summary_schedules_test.dart b/app/test/features/pipelines/pipeline_summary_schedules_test.dart new file mode 100644 index 00000000..027e2e11 --- /dev/null +++ b/app/test/features/pipelines/pipeline_summary_schedules_test.dart @@ -0,0 +1,84 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/pipelines/screen.dart'; +import 'package:pipelines_app/features/schedules/ui/pipeline/schedule_pipeline_wording.dart'; + +import 'fixtures.dart'; + +void main() { + testWidgets('pipeline Summary lists its schedules without changing tabs', ( + tester, + ) async { + final record = { + 'id': 8, + 'revision': 3, + 'name': 'Research batteries', + 'pipeline_id': 1, + 'version': 3, + 'enabled': true, + 'input': {'prompt': 'Find battery chemistry sources'}, + 'workspace': '/srv/research', + 'rule': { + 'every': '24h', + 'days': ['mon', 'wed'], + 'timezone': 'Europe/London', + }, + 'next_due': '2026-10-22T09:00:00Z', + }; + final gateway = FakeGateway((type, fields) { + return switch (type) { + 'list_pipelines' => pipelineListReply([ + pipelineSummary(id: 1, name: 'Alpha review', version: 3), + ]), + 'list_runs' => runListReply([]), + 'get_pipeline' => pipelineDetailReply( + pipelineDetail( + id: 1, + name: 'Alpha review', + version: 3, + latestVersion: 5, + versions: [versionSummary(3), versionSummary(5)], + ), + ), + 'list_schedules' => { + 'type': 'schedules', + 'schedules': [record], + }, + _ => errorReply('unexpected $type'), + }; + }); + tester.view.physicalSize = const Size(1100, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + MaterialApp(home: PipelinesScreen(gateway: gateway)), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('pipeline-row-1'))); + await tester.pumpAndSettle(); + + expect(find.text('Schedules (1)'), findsOneWidget); + expect(find.text('Research batteries'), findsOneWidget); + expect( + find.text('Pinned v3 · Every 24h · mon, wed · Europe/London'), + findsOneWidget, + ); + expect(find.byKey(scheduleAddKey), findsOneWidget); + expect(find.byKey(scheduleRowEditKey(8)), findsOneWidget); + expect(find.byKey(scheduleRowToggleKey(8)), findsOneWidget); + expect(find.byKey(scheduleRowDeleteKey(8)), findsOneWidget); + expect(gateway.callsOf('list_schedules').single.fields, {'pipeline_id': 1}); + + await tester.tap(find.text('Source')); + await tester.pump(); + expect(find.text('name: alpha'), findsOneWidget); + await tester.tap(find.text('Graph')); + await tester.pump(); + await tester.pump(); + expect(find.byKey(scheduleAddKey), findsNothing); + await tester.tap(find.text('Summary')); + await tester.pumpAndSettle(); + expect(find.text('Research batteries'), findsOneWidget); + }); +} diff --git a/app/test/features/pipelines/pipelines_adaptive_test.dart b/app/test/features/pipelines/pipelines_adaptive_test.dart index b131f124..506b101c 100644 --- a/app/test/features/pipelines/pipelines_adaptive_test.dart +++ b/app/test/features/pipelines/pipelines_adaptive_test.dart @@ -153,9 +153,8 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); - final controller = PipelinesController( - PipelinesRepository(gatewayFor(PipelineFixture())), - ); + final gateway = gatewayFor(PipelineFixture()); + final controller = PipelinesController(PipelinesRepository(gateway)); addTearDown(controller.dispose); await controller.openPipeline(1); await tester.pumpWidget( @@ -167,7 +166,11 @@ void main() { child: child!, ), home: Scaffold( - body: PipelineDetailPanel(controller: controller, showBack: true), + body: PipelineDetailPanel( + controller: controller, + gateway: gateway, + showBack: true, + ), ), ), ); diff --git a/app/test/features/pipelines/test_helpers.dart b/app/test/features/pipelines/test_helpers.dart index 7091fd6f..f3d566e2 100644 --- a/app/test/features/pipelines/test_helpers.dart +++ b/app/test/features/pipelines/test_helpers.dart @@ -27,6 +27,7 @@ FakeGateway gatewayFor( fields['version'] as int, )!, ), + 'list_schedules' => {'type': 'schedules', 'schedules': []}, _ => errorReply('unexpected $type'), }, ); diff --git a/app/test/features/schedules/ui/pipeline/schedule_pipeline_section_test.dart b/app/test/features/schedules/ui/pipeline/schedule_pipeline_section_test.dart new file mode 100644 index 00000000..fdf3ce8d --- /dev/null +++ b/app/test/features/schedules/ui/pipeline/schedule_pipeline_section_test.dart @@ -0,0 +1,402 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_wording.dart'; +import 'package:pipelines_app/features/schedules/ui/pipeline/schedule_pipeline_wording.dart'; + +import 'schedule_pipeline_test_support.dart'; + +Future _tapSave(WidgetTester tester) async { + // A focused field keeps itself visible, so drop focus before scrolling the + // form to its actions. + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pumpAndSettle(); + final finder = find.byKey(scheduleEditorSubmitKey); + await tester.ensureVisible(finder); + await tester.pump(); + await tester.tap(finder); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('lists this pipeline schedules with server values and states', ( + tester, + ) async { + final gateway = SectionGateway( + (type, fields) async => schedulesReply([ + sectionRecord(), + sectionRecord( + id: 9, + revision: 1, + name: 'Nightly report', + version: 5, + enabled: false, + prompt: 'Summarise the open issues', + workspace: '/srv/reports', + rule: const { + 'times': ['10:00', '18:30'], + 'days': [], + 'timezone': 'Local', + }, + nextDue: null, + ), + ]), + ); + await pumpScheduleSection(tester, gateway: gateway); + + expect(find.text('Schedules (2)'), findsOneWidget); + expect(find.text('Research batteries'), findsOneWidget); + expect( + find.text('Pinned v2 · Every 24h · mon, wed · Europe/London'), + findsOneWidget, + ); + expect(find.text('Next: Paused'), findsOneWidget); + expect(find.text('Nightly report'), findsOneWidget); + expect( + find.text('Pinned v5 · 10:00, 18:30 · Server timezone'), + findsOneWidget, + ); + expect(find.text('Enabled'), findsOneWidget); + expect(find.text('Paused'), findsOneWidget); + expect(find.text('Next: Paused'), findsOneWidget); + expect(find.byKey(scheduleRowEditKey(8)), findsOneWidget); + expect(find.byKey(scheduleRowToggleKey(9)), findsOneWidget); + expect(gateway.calls.map((call) => call.type), ['list_schedules']); + expect(gateway.calls.single.fields, {'pipeline_id': 4}); + }); + + testWidgets('create validates, keeps a conflict draft and reuses one key', ( + tester, + ) async { + var rows = >[]; + var saves = 0; + final gateway = SectionGateway((type, fields) { + switch (type) { + case 'list_schedules': + return schedulesReply([...rows]); + case 'save_schedule': + saves++; + if (saves == 1) { + throw const ProtocolError('conflict: revision 7 is stale'); + } + final record = Map.from(fields['schedule'] as Map); + final stored = { + ...record, + 'id': 8, + 'revision': 1, + 'name': 'Server truth', + }; + rows = [stored]; + return {'type': 'schedule', 'schedule': stored}; + default: + throw StateError('unexpected $type'); + } + }); + await pumpScheduleSection(tester, gateway: gateway, version: 3); + + expect(find.text('Schedules (0)'), findsOneWidget); + expect( + find.text('No schedules yet. Add one for each topic or recurring task.'), + findsOneWidget, + ); + await tester.tap(find.byKey(scheduleAddKey)); + await tester.pumpAndSettle(); + + final versionField = tester.widget( + find.byKey(scheduleEditorVersionKey), + ); + final workspaceField = tester.widget( + find.byKey(scheduleEditorWorkspaceKey), + ); + expect(versionField.controller?.text, '3'); + expect(workspaceField.controller?.text, '/srv/research'); + + await _tapSave(tester); + expect(gateway.callsOf('save_schedule'), isEmpty); + expect(find.text('Enter a schedule name.'), findsOneWidget); + expect(find.text('Enter a prompt.'), findsOneWidget); + expect(find.byKey(scheduleEditorSubmitKey), findsOneWidget); + + await tester.enterText(find.byKey(scheduleEditorNameKey), 'New schedule'); + await tester.enterText( + find.byKey(scheduleEditorPromptKey), + 'Summarise the release notes.', + ); + await _tapSave(tester); + + final first = gateway.callsOf('save_schedule').single; + final key = first.fields['request_key']; + expect(key, isA()); + expect(key, isNotEmpty); + expect( + find.textContaining('conflict: revision 7 is stale'), + findsOneWidget, + ); + expect(find.textContaining('Your draft is preserved.'), findsOneWidget); + expect(find.byKey(scheduleEditorSubmitKey), findsOneWidget); + expect( + tester + .widget(find.byKey(scheduleEditorNameKey)) + .controller + ?.text, + 'New schedule', + ); + + await _tapSave(tester); + + final savesCalls = gateway.callsOf('save_schedule'); + expect(savesCalls, hasLength(2)); + expect(savesCalls[0].fields['request_key'], key); + expect(savesCalls[1].fields['request_key'], key); + expect(savesCalls[1].fields['schedule'], { + 'id': 0, + 'name': 'New schedule', + 'pipeline_id': 4, + 'version': 3, + 'enabled': true, + 'input': {'prompt': 'Summarise the release notes.'}, + 'workspace': '/srv/research', + 'rule': {'every': '24h'}, + 'notify_mode': 'auto', + }); + + expect(find.byKey(scheduleEditorSubmitKey), findsNothing); + expect(find.text('Server truth'), findsOneWidget); + expect(find.text('New schedule'), findsNothing); + expect(gateway.callsOf('list_schedules'), hasLength(2)); + expect(gateway.callsOf('list_schedules').last.fields, {'pipeline_id': 4}); + }); + + testWidgets( + 'edit starts from the exact record and preserves unknown fields', + (tester) async { + final original = sectionRecord(); + var rows = >[original]; + final gateway = SectionGateway((type, fields) { + switch (type) { + case 'list_schedules': + return schedulesReply([...rows]); + case 'save_schedule': + final record = Map.from(fields['schedule'] as Map); + final stored = {...record, 'revision': 4}; + rows = [stored]; + return {'type': 'schedule', 'schedule': stored}; + default: + throw StateError('unexpected $type'); + } + }); + await pumpScheduleSection(tester, gateway: gateway); + + await tester.tap(find.byKey(scheduleRowEditKey(8))); + await tester.pumpAndSettle(); + expect( + tester + .widget(find.byKey(scheduleEditorNameKey)) + .controller + ?.text, + 'Research batteries', + ); + await tester.enterText(find.byKey(scheduleEditorNameKey), 'Edited topic'); + await _tapSave(tester); + + final call = gateway.callsOf('save_schedule').single; + expect(call.fields.containsKey('request_key'), isFalse); + final sent = call.fields['schedule'] as Map; + expect(sent['id'], 8); + expect(sent['revision'], 3); + expect(sent['name'], 'Edited topic'); + expect(sent['pipeline_id'], 4); + expect(sent['version'], 2); + expect(sent['enabled'], isTrue); + expect(sent['input'], original['input']); + expect(sent['rule'], original['rule']); + expect(sent['future_server_field'], original['future_server_field']); + expect(sent['model'], 'provider/model'); + expect(sent['notify_mode'], 'off'); + expect(find.text('Edited topic'), findsOneWidget); + expect(gateway.callsOf('list_schedules'), hasLength(2)); + }, + ); + + testWidgets('pause sends only the enabled flip and the same revision', ( + tester, + ) async { + final original = sectionRecord(); + var rows = >[original]; + final gateway = SectionGateway((type, fields) { + switch (type) { + case 'list_schedules': + return schedulesReply([...rows]); + case 'save_schedule': + final record = Map.from(fields['schedule'] as Map); + final stored = {...record, 'revision': 4}; + rows = [stored]; + return {'type': 'schedule', 'schedule': stored}; + default: + throw StateError('unexpected $type'); + } + }); + await pumpScheduleSection(tester, gateway: gateway); + + await tester.tap(find.byKey(scheduleRowToggleKey(8))); + await tester.pumpAndSettle(); + + final call = gateway.callsOf('save_schedule').single; + expect(call.fields.containsKey('request_key'), isFalse); + expect(call.fields['schedule'], {...original, 'enabled': false}); + expect(find.text('Paused'), findsOneWidget); + expect(find.text('Next: Paused'), findsOneWidget); + expect(find.byKey(scheduleRowToggleKey(8)), findsOneWidget); + expect(find.text('Enable'), findsOneWidget); + expect(gateway.calls.map((call) => call.type), [ + 'list_schedules', + 'save_schedule', + 'list_schedules', + ]); + }); + + testWidgets('pause refusal stays visible on that row', (tester) async { + final gateway = SectionGateway((type, fields) { + if (type == 'list_schedules') { + return schedulesReply([sectionRecord()]); + } + throw const ProtocolError('conflict: revision 3 is stale'); + }); + await pumpScheduleSection(tester, gateway: gateway); + + await tester.tap(find.byKey(scheduleRowToggleKey(8))); + await tester.pumpAndSettle(); + + expect(find.byKey(scheduleRowErrorKey(8)), findsOneWidget); + expect(find.text('conflict: revision 3 is stale'), findsOneWidget); + expect(find.text('Pause'), findsOneWidget); + expect(gateway.callsOf('list_schedules'), hasLength(1)); + }); + + testWidgets('delete confirms once and sends the exact id and revision', ( + tester, + ) async { + var rows = >[sectionRecord()]; + final gateway = SectionGateway((type, fields) { + switch (type) { + case 'list_schedules': + return schedulesReply([...rows]); + case 'delete_schedule': + expect(fields, {'schedule_id': 8, 'expected_revision': 3}); + rows = []; + return {'type': 'schedule_deleted', 'schedule_id': 8}; + default: + throw StateError('unexpected $type'); + } + }); + await pumpScheduleSection(tester, gateway: gateway); + + await tester.tap(find.byKey(scheduleRowDeleteKey(8))); + await tester.pumpAndSettle(); + expect(find.text('Delete Research batteries?'), findsOneWidget); + expect( + find.text( + 'Future runs only. Run history and active runs will not be deleted.', + ), + findsOneWidget, + ); + await tester.tap(find.byKey(scheduleDeleteKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.callsOf('delete_schedule'), isEmpty); + + await tester.tap(find.byKey(scheduleRowDeleteKey(8))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(scheduleDeleteConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.callsOf('delete_schedule'), hasLength(1)); + expect(find.text('Research batteries'), findsNothing); + expect( + find.text('No schedules yet. Add one for each topic or recurring task.'), + findsOneWidget, + ); + expect(gateway.calls.map((call) => call.type), [ + 'list_schedules', + 'delete_schedule', + 'list_schedules', + ]); + }); + + testWidgets('delete refusal keeps the prompt and shows server words', ( + tester, + ) async { + final gateway = SectionGateway((type, fields) { + if (type == 'list_schedules') { + return schedulesReply([sectionRecord()]); + } + throw const ProtocolError('schedule changed elsewhere'); + }); + await pumpScheduleSection(tester, gateway: gateway); + + await tester.tap(find.byKey(scheduleRowDeleteKey(8))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(scheduleDeleteConfirmKey)); + await tester.pumpAndSettle(); + + expect(find.text('schedule changed elsewhere'), findsOneWidget); + expect(find.byKey(scheduleDeleteErrorKey), findsOneWidget); + expect(find.byKey(scheduleDeleteConfirmKey), findsOneWidget); + expect(gateway.callsOf('list_schedules'), hasLength(1)); + + await tester.tap(find.byKey(scheduleDeleteKeepKey)); + await tester.pumpAndSettle(); + expect(find.text('Research batteries'), findsOneWidget); + }); + + testWidgets('list failure keeps its own words and can retry', (tester) async { + var fail = true; + final gateway = SectionGateway((type, fields) { + if (fail) throw const ProtocolError('socket closed'); + return schedulesReply([sectionRecord()]); + }); + await pumpScheduleSection(tester, gateway: gateway); + + expect(find.text('socket closed'), findsOneWidget); + expect(find.text('Retry'), findsOneWidget); + fail = false; + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + + expect(find.text('Research batteries'), findsOneWidget); + expect(find.text('socket closed'), findsNothing); + }); + + testWidgets('320px at 2x text stays usable on both native hosts', ( + tester, + ) async { + for (final cupertino in [false, true]) { + final gateway = SectionGateway( + (type, fields) async => schedulesReply([ + sectionRecord( + name: 'A very long schedule name that must wrap without overflow', + prompt: + 'A long prompt that also wraps instead of forcing a fixed row ' + 'height or a horizontal scroll.', + ), + ]), + ); + await pumpScheduleSection( + tester, + gateway: gateway, + cupertino: cupertino, + dark: cupertino, + width: 320, + height: 844, + textScale: 2, + ); + + expect(tester.takeException(), isNull); + expect(find.byKey(scheduleAddKey), findsOneWidget); + await tester.ensureVisible(find.byKey(scheduleRowDeleteKey(8))); + await tester.pumpAndSettle(); + expect(find.byKey(scheduleRowEditKey(8)), findsOneWidget); + expect(find.byKey(scheduleRowToggleKey(8)), findsOneWidget); + expect(tester.takeException(), isNull); + } + }); +} diff --git a/app/test/features/schedules/ui/pipeline/schedule_pipeline_test_support.dart b/app/test/features/schedules/ui/pipeline/schedule_pipeline_test_support.dart new file mode 100644 index 00000000..57ab7ffb --- /dev/null +++ b/app/test/features/schedules/ui/pipeline/schedule_pipeline_test_support.dart @@ -0,0 +1,143 @@ +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/pipeline/schedule_pipeline_section.dart'; +import 'package:pipelines_app/features/settings/settings_store.dart'; + +typedef ScheduleSectionHandler = + FutureOr Function(String type, JsonMap fields); + +class SectionCall { + const SectionCall(this.type, this.fields); + final String type; + final JsonMap fields; +} + +/// Records every request and lets the test decide each reply. No socket is +/// opened and no Pipelines server is involved. +class SectionGateway implements ApiGateway { + SectionGateway(this.handler); + + final ScheduleSectionHandler handler; + final calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(SectionCall(type, Map.from(fields))); + return handler(type, Map.from(fields)); + } + + @override + Stream get frames => const Stream.empty(); + + List callsOf(String type) => + calls.where((call) => call.type == type).toList(growable: false); +} + +JsonMap schedulesReply(List items) => { + 'type': 'schedules', + 'schedules': items, +}; + +JsonMap sectionRecord({ + int? id = 8, + int? revision = 3, + String name = 'Research batteries', + int? pipelineId = 4, + int? version = 2, + bool enabled = true, + String prompt = 'Find battery chemistry sources', + String workspace = '/srv/research', + Map rule = const { + 'every': '24h', + 'days': ['mon', 'wed'], + 'timezone': 'Europe/London', + 'future_rule_field': 'kept', + }, + String? nextDue = '2026-10-22T09:00:00Z', +}) => { + 'id': ?id, + 'revision': ?revision, + 'name': name, + 'pipeline_id': ?pipelineId, + 'version': ?version, + 'enabled': enabled, + 'input': { + 'prompt': prompt, + 'custom': {'nested': 'kept'}, + }, + 'workspace': workspace, + 'rule': rule, + 'next_due': ?nextDue, + 'notify_mode': 'off', + 'model': 'provider/model', + 'future_server_field': { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }, +}; + +Widget sectionApp( + Widget section, { + required bool cupertino, + bool dark = false, + double textScale = 1, +}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + final body = SafeArea( + child: ListView(children: [section, const SizedBox(height: 24)]), + ); + if (cupertino) { + return CupertinoApp( + debugShowCheckedModeBanner: false, + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + builder: media, + home: CupertinoPageScaffold(child: body), + ); + } + return MaterialApp( + debugShowCheckedModeBanner: false, + theme: ThemeData(brightness: dark ? Brightness.dark : Brightness.light), + builder: media, + home: Scaffold(body: body), + ); +} + +Future pumpScheduleSection( + WidgetTester tester, { + required SectionGateway gateway, + bool cupertino = false, + bool dark = false, + double width = 390, + double height = 844, + double textScale = 1, + int version = 3, +}) async { + tester.view.physicalSize = Size(width, height); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final section = SchedulePipelineSection( + gateway: gateway, + pipelineId: 4, + version: version, + settingsStore: MemorySettingsStore(workspace: '/srv/research'), + ); + await tester.pumpWidget( + sectionApp(section, cupertino: cupertino, dark: dark, textScale: textScale), + ); + await tester.pumpAndSettle(); +} diff --git a/app/tool/schedule_pipeline_probe.mjs b/app/tool/schedule_pipeline_probe.mjs new file mode 100644 index 00000000..c8119be3 --- /dev/null +++ b/app/tool/schedule_pipeline_probe.mjs @@ -0,0 +1,407 @@ +import { createServer } from 'node:http'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { deepStrictEqual } from 'node:assert/strict'; + +// Real-browser acceptance for the pipeline Summary schedule section. +// +// flutter build web -t tool/schedule_pipeline_probe_app.dart \ +// -o build/schedule_pipeline_probe_web +// OPENCODE_ARTIFACT_DIR= node tool/schedule_pipeline_probe.mjs +// +// The fake gateway and records are in-process; no Pipelines server, +// authentication or real schedule is contacted. + +const root = resolve(process.env.PROBE_WEB_ROOT ?? 'build/schedule_pipeline_probe_web'); +const output = process.env.OPENCODE_ARTIFACT_DIR; +if (!output) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(output, { recursive: true }); +const chromePath = process.env.CHROME_PATH + ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const mime = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.css': 'text/css; charset=utf-8', + '.otf': 'font/otf', + '.ttf': 'font/ttf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.bin': 'application/octet-stream', +}; + +const server = createServer(async (req, res) => { + try { + const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + const path = resolve(root, `.${pathname}`); + if (path !== root && !path.startsWith(root + sep)) { + return res.writeHead(403).end(); + } + const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res + .writeHead(200, { + 'content-type': mime[extname(filePath)] ?? 'application/octet-stream', + 'cache-control': 'no-store', + }) + .end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const origin = `http://127.0.0.1:${server.address().port}`; + +const profile = await mkdtemp(join(tmpdir(), 's1-wire-chrome-')); +const chrome = spawn(chromePath, [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', (data) => { stderr += data; }); + +const waitFor = async (fn, label, attempts = 220) => { + for (let i = 0; i < attempts; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${label}\n${stderr.slice(-1200)}`); +}; + +let ws; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + const pageErrors = []; + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.method === 'Runtime.exceptionThrown') { + pageErrors.push(message.params?.exceptionDetails?.exception?.description ?? 'page exception'); + } + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`); + const target = created.result.targetId; + const session = ( + await send('Target.attachToTarget', { targetId: target, flatten: true }) + ).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + + let width = 390; + let height = 844; + const evaluate = async (expression) => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + if (response.result?.exceptionDetails) { + throw new Error(`Runtime exception: ${JSON.stringify(response.result.exceptionDetails)}`); + } + return response.result?.result?.value; + }; + + const text = () => evaluate(`(() => { + const chunks = []; + for (const el of document.querySelectorAll('[aria-label]')) { + const label = el.getAttribute('aria-label'); + if (label) chunks.push(label); + } + for (const el of document.querySelectorAll('flt-semantics')) { + if (!el.children.length && el.innerText) chunks.push(el.innerText); + } + for (const el of document.querySelectorAll('input, textarea')) { + if (el.getAttribute('aria-label')) chunks.push(el.getAttribute('aria-label') + '=' + el.value); + } + if (document.body?.innerText) chunks.push(document.body.innerText); + return [...new Set(chunks)].join('\\n'); + })()`); + + const assertText = async (needle) => { + try { + await waitFor(async () => (await text()).includes(needle), `text ${JSON.stringify(needle)}`); + } catch (error) { + throw new Error(`${error.message}\nText now:\n${(await text()).slice(0, 4000)}`); + } + }; + const assertNoText = async (needle) => { + if ((await text()).includes(needle)) { + throw new Error(`Unexpected text ${JSON.stringify(needle)}\n${(await text()).slice(0, 4000)}`); + } + }; + + const click = async (needle, { index = 0, optional = false } = {}) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(needle)}; + const nodes = [...document.querySelectorAll('flt-semantics')]; + const matches = nodes.filter((x) => (x.getAttribute('aria-label') || '').trim() === wanted) + .concat(nodes.filter((x) => (x.innerText || '').trim() === wanted)) + .concat(nodes.filter((x) => (x.getAttribute('aria-label') || x.innerText || '').trim().startsWith(wanted))); + const node = matches[${index}]; + if (!node) return false; + node.click(); + return true; + })()`); + if (!clicked && !optional) { + throw new Error(`Could not click ${JSON.stringify(needle)} #${index}\n${(await text()).slice(0, 4000)}`); + } + await delay(400); + return clicked; + }; + + const inputs = () => evaluate(`[...document.querySelectorAll('input,textarea')].map((el) => ({ + label: el.getAttribute('aria-label') || '', + value: el.value, + disabled: el.disabled, + }))`); + + const typeField = async (label, value) => { + const focused = await evaluate(`(() => { + const wanted = ${JSON.stringify(label)}; + const el = [...document.querySelectorAll('input, textarea')].find((input) => { + const name = input.getAttribute('aria-label') || ''; + return name === wanted || name.startsWith(wanted + '\\n'); + }); + if (!el) return false; + el.focus(); + el.select?.(); + el.setSelectionRange?.(0, (el.value || '').length); + return true; + })()`); + if (!focused) throw new Error(`No field ${JSON.stringify(label)}\n${(await text()).slice(0, 4000)}`); + await delay(250); + await send('Input.insertText', { text: value }, session); + await delay(350); + }; + + const state = () => evaluate('globalThis.schedulePipelineProbe ?? null'); + const wheel = async (delta) => { + await send( + 'Input.dispatchMouseEvent', + { type: 'mouseWheel', x: Math.floor(width / 2), y: Math.floor(height / 2), deltaX: 0, deltaY: delta }, + session, + ); + await delay(450); + }; + const captures = []; + const checks = []; + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data; + const file = `${name}.png`; + await writeFile(join(output, file), Buffer.from(data, 'base64')); + captures.push({ name, file, width, height }); + return file; + }; + + const load = async (query, nextWidth, nextHeight) => { + width = nextWidth; + height = nextHeight; + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor: 1, mobile: width < 600 }, + session, + ); + const navigation = await send('Page.navigate', { url: `${origin}/?${query}` }, session); + if (navigation.error || navigation.result?.errorText) { + throw new Error(`Navigation failed: ${JSON.stringify(navigation)}`); + } + await waitFor( + () => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), + 'semantics placeholder', + ); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(1400); + }; + + const saveAtBottom = async () => { + await wheel(1800); + await click('Save schedule'); + await delay(350); + }; + + // One host runs list -> new -> invalid -> valid save -> conflict -> retry, + // then pause and delete against the same fixture. + const runFlow = async (name, { host, brightness = 'platform', scale = 1, width: w, height: h }) => { + await load( + `host=${host}&scale=${scale}${brightness === 'dark' ? '&brightness=dark' : ''}`, + w, + h, + ); + await assertText('Schedules (2)'); + await assertText('Research batteries'); + await assertText('Nightly report'); + await assertText('Pinned v3 · Every 24h · mon, wed · Europe/London'); + await assertText('Pinned v3 · 10:00, 18:30 · Server timezone'); + await capture(`${name}-list`); + checks.push({ check: `${host} listed the pipeline schedules`, lists: (await state()).lists }); + + await click('Add schedule'); + await assertText('Future runs only; does not publish or change the workflow.'); + await capture(`${name}-editor`); + + await saveAtBottom(); + let fields = await inputs(); + if (!fields.find((field) => field.label.startsWith('Name'))?.label.includes('Enter a schedule name.')) { + throw new Error(`Name error missing: ${JSON.stringify(fields)}`); + } + if (!fields.find((field) => field.label.startsWith('Prompt'))?.label.includes('Enter a prompt.')) { + throw new Error(`Prompt error missing: ${JSON.stringify(fields)}`); + } + if ((await state()).saves !== 0) throw new Error('Invalid form sent a save'); + await wheel(-2200); + await capture(`${name}-invalid`); + checks.push({ check: `${host} invalid fields sent nothing`, saves: (await state()).saves }); + + await typeField('Name', 'Probe schedule'); + await typeField('Prompt', 'Summarise the release notes.'); + await saveAtBottom(); + await waitFor(async () => (await state()).saves === 1, 'the accepted create'); + await assertText('Schedules (3)'); + await assertText('Probe schedule'); + const created = await state(); + if (created.lastSaved?.id !== 0 + || created.lastSaved?.pipeline_id !== 4 + || created.lastSaved?.version !== 3 + || created.lastSaved?.workspace !== '/srv/research' + || created.lastSaved?.name !== 'Probe schedule') { + throw new Error(`Create record drifted: ${JSON.stringify(created.lastSaved)}`); + } + if (typeof created.lastRequestKey !== 'string' || !created.lastRequestKey) { + throw new Error(`Create request key missing: ${JSON.stringify(created.lastRequestKey)}`); + } + await capture(`${name}-created`); + checks.push({ + check: `${host} create sent the pinned, workspace-seeded record with one key and refreshed`, + saves: created.saves, + requestKey: created.lastRequestKey, + record: created.lastSaved, + rows: created.rows, + }); + + // First edit is refused; the draft and the server's reason stay visible. + await click('Edit'); + await assertText('Edit schedule'); + await typeField('Name', 'Edited schedule'); + await saveAtBottom(); + await assertText('conflict: revision 3 is stale'); + await assertText('Your draft is preserved.'); + fields = await inputs(); + if (fields.find((field) => field.label.startsWith('Name'))?.value !== 'Edited schedule') { + throw new Error(`Conflict lost the draft: ${JSON.stringify(fields)}`); + } + if ((await state()).saves !== 2) throw new Error('Conflict retried without the operator'); + await capture(`${name}-conflict`); + checks.push({ + check: `${host} conflict kept the draft and showed the server words`, + saves: (await state()).saves, + lastSaved: (await state()).lastSaved, + }); + + await saveAtBottom(); + await waitFor(async () => (await state()).saves === 3, 'the accepted edit'); + await assertText('Edited schedule'); + await assertText('Schedules (3)'); + checks.push({ check: `${host} accepted edit refreshed the list`, saves: (await state()).saves }); + + // Pause sends only the enabled flip and the loaded revision. + const beforePause = (await state()).rows.find((row) => row.name === 'Edited schedule'); + await click('Pause'); + await waitFor(async () => (await state()).saves === 4, 'the accepted pause'); + const pause = (await state()).lastSaved; + if (pause?.enabled !== false || pause?.id !== beforePause.id || pause?.revision !== beforePause.revision) { + throw new Error(`Pause payload drifted: ${JSON.stringify(pause)} vs ${JSON.stringify(beforePause)}`); + } + await assertText('Enable'); + checks.push({ check: `${host} pause sent only enabled with the loaded revision`, pause }); + + // Delete confirms once, then sends the exact id + expected revision. + await click('Delete'); + await assertText('Delete Edited schedule?'); + await assertText('Future runs only. Run history and active runs will not be deleted.'); + await click('Keep schedule'); + if ((await state()).deletes !== 0) throw new Error('Keep deleted a schedule'); + await assertText('Edited schedule'); + await assertNoText('Delete Edited schedule?'); + await click('Delete'); + await click('Delete schedule'); + await waitFor(async () => (await state()).deletes === 1, 'the accepted delete'); + const deleted = (await state()).lastDeleted; + if (deleted?.schedule_id !== beforePause.id || typeof deleted?.expected_revision !== 'number') { + throw new Error(`Delete payload drifted: ${JSON.stringify(deleted)}`); + } + await assertText('Schedules (2)'); + await assertNoText('Edited schedule'); + checks.push({ check: `${host} delete confirmed and sent id + revision`, deleted }); + }; + + await runFlow('s1w-material-390', { host: 'material', width: 390, height: 844 }); + await runFlow('s1w-cupertino-dark-390', { + host: 'cupertino', + brightness: 'dark', + width: 390, + height: 844, + }); + + // Narrow phone at 2x text on the material host. + await load('host=material&scale=2', 320, 844); + await assertText('Schedules (2)'); + await capture('s1w-material-320-2x-list'); + await click('Add schedule'); + await assertText('Future runs only; does not publish or change the workflow.'); + await capture('s1w-material-320-2x-editor-top'); + await wheel(2000); + await capture('s1w-material-320-2x-editor-bottom'); + await assertText('Save schedule'); + checks.push({ check: '320px at 2x kept the section and editor usable', width: 320, scale: 2 }); + + if (pageErrors.length) throw new Error(`Page exceptions: ${JSON.stringify(pageErrors)}`); + const manifest = { + url: origin, + fixture: 'tool/schedule_pipeline_probe_app.dart', + output, + checks, + captures, + }; + await writeFile(join(output, 'manifest.json'), JSON.stringify(manifest, null, 2)); + console.log(JSON.stringify(manifest, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +} diff --git a/app/tool/schedule_pipeline_probe_app.dart b/app/tool/schedule_pipeline_probe_app.dart new file mode 100644 index 00000000..d9007dce --- /dev/null +++ b/app/tool/schedule_pipeline_probe_app.dart @@ -0,0 +1,208 @@ +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/ui/pipeline/schedule_pipeline_section.dart'; +import 'package:pipelines_app/features/settings/settings_store.dart'; + +/// Isolated browser fixture for the pipeline Summary schedule section. +/// +/// flutter build web -t tool/schedule_pipeline_probe_app.dart +/// +/// Query: `host=cupertino`, `brightness=dark`, `scale=2`. The fake gateway keeps +/// its schedules in memory, accepts one create, refuses the first edit with a +/// stale revision, then accepts the retry. It never opens a socket or contacts a +/// real server. State is published at `globalThis.schedulePipelineProbe`. +void main() => runApp(const _ProbeApp()); + +class _Refusal implements Exception { + const _Refusal(); + + @override + String toString() => 'conflict: revision 3 is stale'; +} + +class _ProbeApp extends StatelessWidget { + const _ProbeApp(); + + @override + Widget build(BuildContext context) { + final parameters = Uri.base.queryParameters; + final cupertino = parameters['host'] == 'cupertino'; + final dark = parameters['brightness'] == 'dark'; + final scale = double.tryParse(parameters['scale'] ?? '') ?? 1.0; + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: app!, + ); + final gateway = _FixtureGateway(); + final section = SchedulePipelineSection( + gateway: gateway, + pipelineId: 4, + version: 3, + settingsStore: MemorySettingsStore(workspace: '/srv/research'), + ); + final body = SafeArea( + child: ListView(children: [section, const SizedBox(height: 24)]), + ); + if (cupertino) { + return CupertinoApp( + debugShowCheckedModeBanner: false, + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + builder: media, + home: CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar( + middle: Text('Alpha review'), + ), + child: body, + ), + ); + } + return MaterialApp( + debugShowCheckedModeBanner: false, + theme: ThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + platform: TargetPlatform.android, + ), + builder: media, + home: Scaffold( + appBar: AppBar(title: const Text('Alpha review')), + body: body, + ), + ); + } +} + +class _FixtureGateway implements ApiGateway { + _FixtureGateway() { + _publish(); + } + + final List> _rows = [ + { + 'id': 8, + 'revision': 3, + 'name': 'Research batteries', + 'pipeline_id': 4, + 'version': 3, + 'enabled': true, + 'input': {'prompt': 'Find battery chemistry sources'}, + 'workspace': '/srv/research', + 'rule': { + 'every': '24h', + 'days': ['mon', 'wed'], + 'timezone': 'Europe/London', + }, + 'next_due': '2026-10-22T09:00:00Z', + }, + { + 'id': 9, + 'revision': 1, + 'name': 'Nightly report', + 'pipeline_id': 4, + 'version': 3, + 'enabled': false, + 'input': {'prompt': 'Summarise the open issues'}, + 'workspace': '/srv/reports', + 'rule': { + 'times': ['10:00', '18:30'], + 'days': [], + 'timezone': 'Local', + }, + }, + ]; + int _nextId = 10; + int _lists = 0; + int _saves = 0; + int _deletes = 0; + bool _refuseEdit = true; + JsonMap? _lastSaved; + JsonMap? _lastDeleted; + String? _lastRequestKey; + + void _publish() { + globalContext.setProperty( + 'schedulePipelineProbe'.toJS, + { + 'lists': _lists, + 'saves': _saves, + 'deletes': _deletes, + 'lastSaved': _lastSaved, + 'lastDeleted': _lastDeleted, + 'lastRequestKey': _lastRequestKey, + 'rows': [ + for (final row in _rows) + { + 'id': row['id'], + 'revision': row['revision'], + 'name': row['name'], + 'enabled': row['enabled'], + }, + ], + }.jsify(), + ); + } + + @override + Future call(String type, [JsonMap fields = const {}]) async { + switch (type) { + case 'list_schedules': + _lists++; + _publish(); + return { + 'type': 'schedules', + 'schedules': [ + for (final row in _rows) Map.from(row), + ], + }; + case 'save_schedule': + _saves++; + final sent = Map.from(fields['schedule'] as Map); + _lastSaved = sent; + _lastRequestKey = fields['request_key'] as String?; + if (sent['id'] == 0) { + final stored = { + ...sent, + 'id': _nextId++, + 'revision': 1, + 'next_due': '2026-10-23T09:00:00Z', + }; + _rows.add(stored); + _publish(); + return {'type': 'schedule', 'schedule': stored}; + } + if (_refuseEdit && sent['id'] == 8) { + _refuseEdit = false; + _publish(); + throw const _Refusal(); + } + final index = _rows.indexWhere((row) => row['id'] == sent['id']); + final stored = { + ...sent, + 'revision': (sent['revision'] as int) + 1, + 'next_due': sent['enabled'] == true ? '2026-10-23T09:00:00Z' : null, + }; + if (index >= 0) _rows[index] = stored; + _publish(); + return {'type': 'schedule', 'schedule': stored}; + case 'delete_schedule': + _deletes++; + final id = fields['schedule_id']; + _lastDeleted = Map.from(fields); + _rows.removeWhere((row) => row['id'] == id); + _publish(); + return {'type': 'schedule_deleted', 'schedule_id': id}; + default: + throw StateError('unexpected $type'); + } + } + + @override + Stream get frames => const Stream.empty(); +}