diff --git a/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart b/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart new file mode 100644 index 00000000..044a98e3 --- /dev/null +++ b/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart @@ -0,0 +1,191 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../ui/adaptive/host.dart'; + +/// Secondary text under a field, using the host's own colours and text theme. +TextStyle scheduleEditorSecondaryStyle(BuildContext context) { + if (usesCupertinoHost(context)) { + return CupertinoTheme.of(context).textTheme.textStyle.copyWith( + fontSize: 14, + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ); + } + final theme = Theme.of(context); + return (theme.textTheme.bodySmall ?? const TextStyle()).copyWith( + color: theme.colorScheme.onSurfaceVariant, + ); +} + +/// The host's semantic error colour, never a form-specific palette. +TextStyle scheduleEditorErrorStyle(BuildContext context) { + if (usesCupertinoHost(context)) { + return CupertinoTheme.of(context).textTheme.textStyle.copyWith( + color: CupertinoColors.systemRed.resolveFrom(context), + ); + } + return TextStyle(color: Theme.of(context).colorScheme.error); +} + +/// A wrapping label above its control, with optional helper and field error. +/// +/// The browser puts the label in a sibling span, so a native floating label +/// would invent different words and truncate at large text sizes. +class ScheduleEditorField extends StatelessWidget { + const ScheduleEditorField({ + super.key, + required this.label, + required this.child, + this.helper, + this.error, + }); + + final String label; + final Widget child; + final String? helper; + final String? error; + + @override + Widget build(BuildContext context) { + final labelStyle = usesCupertinoHost(context) + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodyMedium; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(label, style: labelStyle), + const SizedBox(height: 6), + child, + if (helper case final text?) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text(text, style: scheduleEditorSecondaryStyle(context)), + ), + if (error case final text?) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text(text, style: scheduleEditorErrorStyle(context)), + ), + ], + ); + } +} + +/// One-line or multiline text input in the host's native field style. +class ScheduleEditorTextField extends StatelessWidget { + const ScheduleEditorTextField({ + super.key, + required this.label, + required this.controller, + required this.onChanged, + this.fieldKey, + this.keyboardType, + this.minLines = 1, + this.maxLines = 1, + this.enabled = true, + this.helper, + this.error, + this.textInputAction, + }); + + final String label; + final TextEditingController controller; + final ValueChanged onChanged; + final Key? fieldKey; + final TextInputType? keyboardType; + final int? minLines; + final int? maxLines; + final bool enabled; + final String? helper; + final String? error; + final TextInputAction? textInputAction; + + @override + Widget build(BuildContext context) { + final field = usesCupertinoHost(context) + ? CupertinoTextField( + key: fieldKey, + controller: controller, + enabled: enabled, + keyboardType: keyboardType, + minLines: minLines, + maxLines: maxLines, + textInputAction: textInputAction, + onChanged: onChanged, + ) + : TextField( + key: fieldKey, + controller: controller, + enabled: enabled, + keyboardType: keyboardType, + minLines: minLines, + maxLines: maxLines, + textInputAction: textInputAction, + onChanged: onChanged, + ); + return MergeSemantics( + child: ScheduleEditorField( + label: label, + helper: helper, + error: error, + child: field, + ), + ); + } +} + +/// A native switch with a wrapping label and an explanatory helper. +class ScheduleEditorSwitchField extends StatelessWidget { + const ScheduleEditorSwitchField({ + super.key, + required this.label, + required this.value, + required this.onChanged, + this.helper, + this.enabled = true, + this.switchKey, + }); + + final String label; + final bool value; + final ValueChanged onChanged; + final String? helper; + final bool enabled; + final Key? switchKey; + + @override + Widget build(BuildContext context) { + final control = usesCupertinoHost(context) + ? CupertinoSwitch( + key: switchKey, + value: value, + onChanged: enabled ? onChanged : null, + ) + : Switch( + key: switchKey, + value: value, + onChanged: enabled ? onChanged : null, + ); + return MergeSemantics( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded(child: Text(label)), + const SizedBox(width: 12), + control, + ], + ), + if (helper case final text?) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text(text, style: scheduleEditorSecondaryStyle(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 new file mode 100644 index 00000000..8862e3d6 --- /dev/null +++ b/app/lib/features/schedules/ui/editor/schedule_editor_form.dart @@ -0,0 +1,234 @@ +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 '../../domain/schedule_rule.dart'; +import 'schedule_editor_form_body.dart'; +import 'schedule_editor_wording.dart'; + +/// The server's refusal, verbatim, plus the browser's preservation promise. +String scheduleEditorRefusal(Object error) { + final reason = '$error'.trim(); + return '${reason.isEmpty ? 'The schedule was not saved.' : reason} ' + '$scheduleEditorDraftPreserved'; +} + +/// One native form over a landed [ScheduleDraft]. +/// +/// The form owns only editable controls: it mutates the draft on submit, asks +/// the draft to validate and assemble the exact record, and calls [onSubmit] +/// only with a non-null record. It never talks to a repository, route or +/// scheduler, and an async refusal leaves every typed value in place. +class ScheduleEditorForm extends StatefulWidget { + const ScheduleEditorForm({ + super.key, + required this.draft, + required this.onSubmit, + this.onCancel, + this.title, + }); + + final ScheduleDraft draft; + final Future Function(JsonMap record) onSubmit; + final VoidCallback? onCancel; + final String? title; + + @override + State createState() => _ScheduleEditorFormState(); +} + +class _ScheduleEditorFormState extends State { + late final TextEditingController _name; + late final TextEditingController _prompt; + late final TextEditingController _version; + late final TextEditingController _workspace; + late final TextEditingController _every; + late final TextEditingController _times; + late final TextEditingController _timezone; + late ScheduleTimerMode _mode; + late List _days; + late bool _enabled; + late String _notifyMode; + + Map _errors = const {}; + String? _refusal; + bool _sending = false; + + @override + void initState() { + super.initState(); + final draft = widget.draft; + _name = TextEditingController(text: draft.name); + _prompt = TextEditingController(text: draft.prompt); + _version = TextEditingController(text: draft.version); + _workspace = TextEditingController(text: draft.workspace); + _every = TextEditingController(text: draft.every); + _times = TextEditingController(text: draft.times); + _timezone = TextEditingController(text: draft.timezone); + _mode = draft.mode; + _days = [...draft.days]; + _enabled = draft.enabled; + _notifyMode = draft.notifyMode; + } + + @override + void dispose() { + for (final controller in [ + _name, + _prompt, + _version, + _workspace, + _every, + _times, + _timezone, + ]) { + controller.dispose(); + } + super.dispose(); + } + + String get _heading => + widget.title ?? + (widget.draft.source == null + ? scheduleEditorAddTitle + : scheduleEditorEditTitle); + + void _clearError(String field) { + if (!_errors.containsKey(field)) return; + setState(() => _errors = {..._errors}..remove(field)); + } + + void _applyToDraft() { + widget.draft + ..name = _name.text + ..prompt = _prompt.text + ..version = _version.text + ..workspace = _workspace.text + ..enabled = _enabled + ..mode = _mode + ..every = _every.text + ..times = _times.text + ..days = [ + for (final day in scheduleDays) + if (_days.contains(day)) day, + ] + ..timezone = _timezone.text + ..notifyMode = _notifyMode; + } + + Future _submit() async { + if (_sending) return; + setState(() => _refusal = null); + _applyToDraft(); + final result = widget.draft.build(); + if (!result.isValid) { + setState(() => _errors = result.errors); + return; + } + setState(() { + _errors = const {}; + _sending = true; + }); + try { + await widget.onSubmit(result.record!); + } catch (error) { + if (!mounted) return; + setState(() { + _sending = false; + _refusal = scheduleEditorRefusal(error); + }); + return; + } + if (mounted) setState(() => _sending = false); + } + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + return ScheduleEditorFormBody( + heading: _heading, + name: _name, + prompt: _prompt, + version: _version, + workspace: _workspace, + every: _every, + times: _times, + timezone: _timezone, + mode: _mode, + days: _days, + enabled: _enabled, + notifyMode: _notifyMode, + errors: _errors, + sending: _sending, + refusal: _refusal, + onModeChanged: (mode) => setState(() { + _mode = mode; + _errors = {..._errors} + ..remove('every') + ..remove('times'); + }), + onDayToggled: (day) => setState(() { + _days = [..._days]; + _days.contains(day) ? _days.remove(day) : _days.add(day); + _errors = {..._errors}..remove('days'); + }), + onEnabledChanged: (enabled) => setState(() => _enabled = enabled), + onNotifyChanged: (mode) => setState(() { + _notifyMode = mode; + _errors = {..._errors}..remove('notifyMode'); + }), + onEdited: _clearError, + actions: Wrap( + alignment: WrapAlignment.end, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 12, + runSpacing: 8, + children: [ + if (widget.onCancel != null) + _cancelButton(cupertino) + else + const SizedBox.shrink(), + _saveButton(cupertino), + ], + ), + ); + } + + Widget _cancelButton(bool cupertino) { + final onPressed = _sending ? null : widget.onCancel; + if (cupertino) { + return CupertinoButton( + key: scheduleEditorCancelKey, + padding: EdgeInsets.zero, + onPressed: onPressed, + child: const Text(scheduleEditorCancelLabel), + ); + } + return TextButton( + key: scheduleEditorCancelKey, + onPressed: onPressed, + child: const Text(scheduleEditorCancelLabel), + ); + } + + Widget _saveButton(bool cupertino) { + final label = Text( + _sending ? scheduleEditorSendingLabel : scheduleEditorSubmitLabel, + ); + final onPressed = _sending ? null : _submit; + if (cupertino) { + return CupertinoButton.filled( + key: scheduleEditorSubmitKey, + onPressed: onPressed, + child: label, + ); + } + return FilledButton( + key: scheduleEditorSubmitKey, + onPressed: onPressed, + child: label, + ); + } +} 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 new file mode 100644 index 00000000..5b4a2f19 --- /dev/null +++ b/app/lib/features/schedules/ui/editor/schedule_editor_form_body.dart @@ -0,0 +1,229 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../ui/adaptive/host.dart'; +import '../../domain/editor/schedule_draft.dart'; +import 'schedule_editor_fields.dart'; +import 'schedule_editor_selectors.dart'; +import 'schedule_editor_wording.dart'; + +/// The visible schedule editor column: native fields, field errors and the +/// Cancel/Save actions. State stays in `ScheduleEditorForm`; this widget only +/// renders the values and forwards edits. +class ScheduleEditorFormBody extends StatelessWidget { + const ScheduleEditorFormBody({ + super.key, + required this.heading, + required this.name, + required this.prompt, + required this.version, + required this.workspace, + required this.every, + required this.times, + required this.timezone, + required this.mode, + required this.days, + required this.enabled, + required this.notifyMode, + required this.errors, + required this.sending, + this.refusal, + required this.onModeChanged, + required this.onDayToggled, + required this.onEnabledChanged, + required this.onNotifyChanged, + required this.onEdited, + required this.actions, + }); + + final String heading; + final TextEditingController name; + final TextEditingController prompt; + final TextEditingController version; + final TextEditingController workspace; + final TextEditingController every; + final TextEditingController times; + final TextEditingController timezone; + final ScheduleTimerMode mode; + final List days; + final bool enabled; + final String notifyMode; + final Map errors; + final bool sending; + final String? refusal; + final ValueChanged onModeChanged; + final ValueChanged onDayToggled; + final ValueChanged onEnabledChanged; + final ValueChanged onNotifyChanged; + final ValueChanged onEdited; + final Widget actions; + + static const _gap = SizedBox(height: 16); + static const _timerOptions = [ + ScheduleEditorChoice(ScheduleTimerMode.interval, 'Interval'), + ScheduleEditorChoice(ScheduleTimerMode.clock, 'Clock times'), + ]; + + List> get _notifyOptions { + const values = ['auto', 'on', 'off']; + return [ + if (!values.contains(notifyMode)) + ScheduleEditorChoice(notifyMode, notifyMode), + for (final value in values) ScheduleEditorChoice(value, value), + ]; + } + + Widget _textField({ + required Key key, + required String label, + required TextEditingController controller, + required String field, + String? error, + int minLines = 1, + int? maxLines = 1, + TextInputType? keyboardType, + TextInputAction? textInputAction, + }) => ScheduleEditorTextField( + fieldKey: key, + label: label, + controller: controller, + enabled: !sending, + minLines: minLines, + maxLines: maxLines, + keyboardType: keyboardType, + textInputAction: textInputAction, + error: error, + onChanged: (_) => onEdited(field), + ); + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + final titleStyle = cupertino + ? CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle + : Theme.of(context).textTheme.titleLarge; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(heading, style: titleStyle), + const SizedBox(height: 8), + Text(scheduleEditorNote, style: scheduleEditorSecondaryStyle(context)), + _gap, + _textField( + key: scheduleEditorNameKey, + label: scheduleEditorNameLabel, + controller: name, + field: 'name', + error: errors['name'], + textInputAction: TextInputAction.next, + ), + _gap, + _textField( + key: scheduleEditorPromptKey, + label: scheduleEditorPromptLabel, + controller: prompt, + field: 'prompt', + error: errors['prompt'], + minLines: 3, + maxLines: null, + keyboardType: TextInputType.multiline, + ), + _gap, + _textField( + key: scheduleEditorVersionKey, + label: scheduleEditorVersionLabel, + controller: version, + field: 'version', + error: errors['version'], + keyboardType: TextInputType.number, + textInputAction: TextInputAction.next, + ), + _gap, + _textField( + key: scheduleEditorWorkspaceKey, + label: scheduleEditorWorkspaceLabel, + controller: workspace, + field: 'workspace', + error: errors['workspace'], + textInputAction: TextInputAction.next, + ), + _gap, + ScheduleEditorChoiceField( + fieldKey: scheduleEditorTimerKey, + label: scheduleEditorTimerLabel, + value: mode, + options: _timerOptions, + enabled: !sending, + onChanged: onModeChanged, + ), + _gap, + if (mode == ScheduleTimerMode.interval) + _textField( + key: scheduleEditorEveryKey, + label: scheduleEditorEveryLabel, + controller: every, + field: 'every', + error: errors['every'], + ) + else + _textField( + key: scheduleEditorTimesKey, + label: scheduleEditorTimesLabel, + controller: times, + field: 'times', + error: errors['times'], + ), + _gap, + ScheduleEditorDaysField( + label: scheduleEditorDaysLabel, + days: days, + enabled: !sending, + error: errors['days'], + onToggle: onDayToggled, + ), + _gap, + _textField( + key: scheduleEditorTimezoneKey, + label: scheduleEditorTimezoneLabel, + controller: timezone, + field: 'timezone', + error: errors['timezone'], + ), + _gap, + ScheduleEditorSwitchField( + switchKey: scheduleEditorEnabledKey, + label: scheduleEditorEnabledLabel, + helper: scheduleEditorEnabledNote, + value: enabled, + enabled: !sending, + onChanged: onEnabledChanged, + ), + _gap, + ScheduleEditorChoiceField( + fieldKey: scheduleEditorNotifyKey, + label: scheduleEditorNotificationsLabel, + value: notifyMode, + options: _notifyOptions, + enabled: !sending, + error: errors['notifyMode'], + onChanged: onNotifyChanged, + ), + if (refusal ?? errors['record'] ?? errors['pipelineId'] + case final error?) ...[ + _gap, + Semantics( + liveRegion: true, + child: Text( + error, + key: scheduleEditorErrorKey, + style: scheduleEditorErrorStyle(context), + ), + ), + ], + _gap, + actions, + ], + ); + } +} diff --git a/app/lib/features/schedules/ui/editor/schedule_editor_selectors.dart b/app/lib/features/schedules/ui/editor/schedule_editor_selectors.dart new file mode 100644 index 00000000..637689fb --- /dev/null +++ b/app/lib/features/schedules/ui/editor/schedule_editor_selectors.dart @@ -0,0 +1,200 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../ui/adaptive/host.dart'; +import '../../domain/schedule_rule.dart'; +import 'schedule_editor_fields.dart'; + +/// Day checkbox keys, shared with tests and the browser fixture. +ValueKey scheduleEditorDayKey(String day) => + ValueKey('schedule-editor-day-$day'); + +/// One option of a [ScheduleEditorChoiceField]. +class ScheduleEditorChoice { + const ScheduleEditorChoice(this.value, this.label); + + final T value; + final String label; +} + +/// A native drop-down on Material and a native action sheet on Cupertino. +class ScheduleEditorChoiceField extends StatelessWidget { + const ScheduleEditorChoiceField({ + super.key, + required this.label, + required this.value, + required this.options, + required this.onChanged, + this.enabled = true, + this.helper, + this.error, + this.fieldKey, + }); + + final String label; + final T value; + final List> options; + final ValueChanged onChanged; + final bool enabled; + final String? helper; + final String? error; + final Key? fieldKey; + + String get _selectedLabel { + for (final option in options) { + if (option.value == value) return option.label; + } + return ''; + } + + Future _choose(BuildContext context) async { + final chosen = await showCupertinoModalPopup( + context: context, + builder: (sheetContext) => CupertinoActionSheet( + title: Text(label), + actions: [ + for (final option in options) + CupertinoActionSheetAction( + onPressed: () => Navigator.pop(sheetContext, option.value), + child: Text(option.label), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.pop(sheetContext), + child: const Text('Cancel'), + ), + ), + ); + if (chosen != null) onChanged(chosen); + } + + @override + Widget build(BuildContext context) { + final control = usesCupertinoHost(context) + ? CupertinoButton( + key: fieldKey, + padding: EdgeInsets.zero, + onPressed: enabled ? () => _choose(context) : null, + child: Row( + children: [ + Expanded(child: Text(_selectedLabel)), + const Icon(CupertinoIcons.chevron_down), + ], + ), + ) + : DropdownButtonFormField( + key: fieldKey, + initialValue: value, + isExpanded: true, + items: [ + for (final option in options) + DropdownMenuItem( + value: option.value, + child: Text(option.label), + ), + ], + onChanged: enabled + ? (chosen) { + if (chosen != null) onChanged(chosen); + } + : null, + ); + return MergeSemantics( + child: ScheduleEditorField( + label: label, + helper: helper, + error: error, + child: control, + ), + ); + } +} + +/// Weekday checkboxes in a wrapping row; no selection means every day. +class ScheduleEditorDaysField extends StatelessWidget { + const ScheduleEditorDaysField({ + super.key, + required this.label, + required this.days, + required this.onToggle, + this.enabled = true, + this.error, + }); + + final String label; + final List days; + final ValueChanged onToggle; + final bool enabled; + final String? error; + + @override + Widget build(BuildContext context) { + return ScheduleEditorField( + label: label, + error: error, + child: Wrap( + spacing: 12, + runSpacing: 8, + children: [ + for (final day in scheduleDays) + _DayToggle( + day: day, + selected: days.contains(day), + enabled: enabled, + onTap: () => onToggle(day), + ), + ], + ), + ); + } +} + +class _DayToggle extends StatelessWidget { + const _DayToggle({ + required this.day, + required this.selected, + required this.enabled, + required this.onTap, + }); + + final String day; + final bool selected; + final bool enabled; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + final checkbox = cupertino + ? CupertinoCheckbox( + key: scheduleEditorDayKey(day), + value: selected, + onChanged: enabled ? (_) => onTap() : null, + ) + : Checkbox( + key: scheduleEditorDayKey(day), + value: selected, + onChanged: enabled ? (_) => onTap() : null, + ); + final content = Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [checkbox, const SizedBox(width: 4), Text(day)], + ), + ); + return MergeSemantics( + child: cupertino + ? GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: enabled ? onTap : null, + child: content, + ) + : InkWell( + borderRadius: BorderRadius.circular(8), + onTap: enabled ? onTap : null, + child: content, + ), + ); + } +} diff --git a/app/lib/features/schedules/ui/editor/schedule_editor_wording.dart b/app/lib/features/schedules/ui/editor/schedule_editor_wording.dart new file mode 100644 index 00000000..1fa78e52 --- /dev/null +++ b/app/lib/features/schedules/ui/editor/schedule_editor_wording.dart @@ -0,0 +1,45 @@ +import 'package:flutter/widgets.dart'; + +/// Browser wording and stable keys for the saved-schedule editor, kept +/// verbatim from `web/src/views/schedules.js`. +const scheduleEditorAddTitle = 'Add schedule'; +const scheduleEditorEditTitle = 'Edit schedule'; +const scheduleEditorNote = + 'Future runs only; does not publish or change the workflow. ' + 'Saving does not start a run.'; +const scheduleEditorNameLabel = 'Name'; +const scheduleEditorPromptLabel = 'Prompt'; +const scheduleEditorVersionLabel = 'Pinned version'; +const scheduleEditorWorkspaceLabel = 'Server workspace'; +const scheduleEditorTimerLabel = 'Timer'; +const scheduleEditorEveryLabel = 'Interval (at least 1m)'; +const scheduleEditorTimesLabel = 'Clock times (24h, comma separated)'; +const scheduleEditorDaysLabel = 'Weekdays (none means every day)'; +const scheduleEditorTimezoneLabel = 'Timezone (blank uses server timezone)'; +const scheduleEditorEnabledLabel = 'Enabled'; +const scheduleEditorEnabledNote = + 'Enabled schedules start future runs automatically, including model ' + 'usage and the workflow’s permitted tools.'; +const scheduleEditorNotificationsLabel = 'Notifications'; +const scheduleEditorSubmitLabel = 'Save schedule'; +const scheduleEditorSendingLabel = 'Saving…'; +const scheduleEditorCancelLabel = 'Cancel'; +const scheduleEditorDraftPreserved = + 'Your draft is preserved. If this schedule changed elsewhere, reopen it ' + 'before retrying.'; + +const scheduleEditorNameKey = ValueKey('schedule-editor-name'); +const scheduleEditorPromptKey = ValueKey('schedule-editor-prompt'); +const scheduleEditorVersionKey = ValueKey('schedule-editor-version'); +const scheduleEditorWorkspaceKey = ValueKey( + 'schedule-editor-workspace', +); +const scheduleEditorTimerKey = ValueKey('schedule-editor-timer'); +const scheduleEditorEveryKey = ValueKey('schedule-editor-every'); +const scheduleEditorTimesKey = ValueKey('schedule-editor-times'); +const scheduleEditorTimezoneKey = ValueKey('schedule-editor-timezone'); +const scheduleEditorEnabledKey = ValueKey('schedule-editor-enabled'); +const scheduleEditorNotifyKey = ValueKey('schedule-editor-notify'); +const scheduleEditorSubmitKey = ValueKey('schedule-editor-submit'); +const scheduleEditorCancelKey = ValueKey('schedule-editor-cancel'); +const scheduleEditorErrorKey = ValueKey('schedule-editor-error'); diff --git a/app/notes/S1-form.md b/app/notes/S1-form.md new file mode 100644 index 00000000..ac572fbc --- /dev/null +++ b/app/notes/S1-form.md @@ -0,0 +1,187 @@ +# S1-form — native saved-schedule form + +## What changed + +New files only. No existing feature, shell, route, `main`, pubspec, server, `web/`, +Android/iOS or deployment source was edited. + +| File | Lines | Responsibility | +| --- | ---: | --- | +| `lib/features/schedules/ui/editor/schedule_editor_form.dart` | 234 | state/controllers, submit/validation/refusal, native Cancel/Save actions | +| `lib/features/schedules/ui/editor/schedule_editor_form_body.dart` | 229 | visible column: heading, note, native fields, live error slot | +| `lib/features/schedules/ui/editor/schedule_editor_fields.dart` | 191 | wrapping label shell, native text field/switch, host secondary/error styles | +| `lib/features/schedules/ui/editor/schedule_editor_selectors.dart` | 200 | native timer/notification menus and weekday checkboxes | +| `lib/features/schedules/ui/editor/schedule_editor_wording.dart` | 45 | verbatim browser copy and stable keys | +| `test/features/schedules/ui/editor/schedule_editor_form_test.dart` | 162 | invalid/create/clock/edit record tests | +| `test/features/schedules/ui/editor/schedule_editor_interaction_test.dart` | 164 | refusal, duplicate submit, Cupertino fields/switch/day, Cancel | +| `test/features/schedules/ui/editor/schedule_editor_layout_test.dart` | 80 | 320px/2x wrapping and native dark Cupertino | +| `test/features/schedules/ui/editor/schedule_editor_harness.dart` | 82 | 390/320 Material and Cupertino hosts | +| `tool/schedule_editor_probe_app.dart` | 170 | standalone local fixture with refusing/accepted fake callback | +| `tool/schedule_editor_probe.mjs` | 368 | real Chrome interaction and seven captures | + +The original aim was two production files. The landing draft, the form state, the +native control primitives, the selectors and the verbatim copy do not fit under +the working agreement's 250-line aim together, so they are split by +responsibility rather than into arbitrary fragments. No generic form framework, +inherited controller or schema was introduced; every file is specific to saved +schedules. + +## Behavior + +`ScheduleEditorForm` binds the landed `ScheduleDraft` and nothing else. It opens +with the draft's current values and mutates only the editable fields on submit. +It then calls `draft.build()`: + +- invalid draft — the returned field errors are shown under their controls and + the injected callback is **not** called; there is no partial record; +- valid draft — every control is disabled, Save reads `Saving…`, and + `onSubmit(record)` receives the exact non-null `build()` record once; +- async refusal — controls re-enable, typed controller values stay verbatim, + and the form shows `" Your draft is preserved. If this schedule + changed elsewhere, reopen it before retrying."` (a blank reason gets `The + schedule was not saved.`). The line is a live-region semantics node, so it is + announced like the browser's `role="alert"`; the browser probe asserts its + visible text after scrolling to it. + +After an accepted callback the form re-enables; the integrating caller owns +closing/replacing it, exactly as the web editor closes its modal on success. No +close/route/save logic exists in this slice. + +The form reads its draft once, in `initState` (the Material selectors also take +an `initialValue`). A caller that reuses the widget with a different draft must +give it a new key, e.g. by operation or `draft.id`, so the controls reinitialise; +mutating the draft in place without a new key is not reflected in the UI. + +Editable in this slice: name, prompt, pinned version, absolute server workspace, +timer mode, interval, clock times, weekdays, timezone, enabled and notification +mode. `draft.source`/`pipelineId` are not editable here. The advanced run options +(`model`, `stage_models`, other input keys, `write_paths`, `allow_tools`, `title`, +`output_format`) are not rendered and are **preserved exactly** because the +landed draft starts every edit from the server snapshot. A create still emits the +web sentinel `id: 0`; an edit keeps its exact `id` and `revision`. + +Weekday toggles send one day key per interaction and the form applies them in +server weekday order, so two quick taps cannot lose the first selection. A raw +notification value outside `auto|on|off` stays visible/selectable and is then +rejected by the draft's validation rather than crashing a dropdown assertion. + +## Native presentation + +- Labels are wrapping text above each control, matching the browser's sibling + label word and avoiding a floating-label ellipsis at 2x text. Helper text and + field errors wrap below the control; no fixed control/row heights. +- Material: `TextField`, `Switch`, `Checkbox`, `DropdownButtonFormField`, + `TextButton`, `FilledButton`. +- Cupertino: `CupertinoTextField`, `CupertinoSwitch`, `CupertinoCheckbox`, + `CupertinoButton` menuing through `CupertinoActionSheet`, plus the same + `CupertinoButton` actions. +- Typography and colours come from `Theme`/`CupertinoTheme` semantic roles and + dynamic label/secondary/error colours. Material helpers use `bodySmall`; the + Cupertino secondary style stays on the theme's text style at the native 14pt + detail size and is still scaled by the text scaler. No bespoke palette or + control clone was added. +- The dark Cupertino fixture is a real `CupertinoApp` with + `CupertinoThemeData(brightness: dark)`; its base page background is the native + `systemBackground` black, while fields, labels, blue actions and the green + switch resolve from the dark Cupertino roles. The widget test also asserts the + dark brightness, dark label colour and that no Material control is present. + +## Browser fixture + +`tool/schedule_editor_probe_app.dart` is standalone: an in-process +`ScheduleDraft.create` (pipeline 4, version 2, `/srv/research`, +`Europe/London`) and a fake `onSubmit`. The first valid submit is refused after +900 ms; the retry is accepted. The state is published at +`globalThis.scheduleEditorProbe`; the accepted record is rendered on the page. +No socket, server, authentication or real schedule is involved. + +## Checks actually run + +``` +dart format lib/features/schedules/ui/editor test/features/schedules/ui/editor \ + tool/schedule_editor_probe_app.dart # clean +flutter analyze # No issues found! +flutter test test/features/schedules # 69 passed +flutter test # 686 before merging main; + # 704 on the merged tree +flutter build web # ✓ Built build/web +flutter build web -t tool/schedule_editor_probe_app.dart \ + -o build/schedule_editor_probe_web # ✓ Built +node --check tool/schedule_editor_probe.mjs # clean +OPENCODE_ARTIFACT_DIR=…/78/public/s1-form-captures \ + node tool/schedule_editor_probe.mjs # all checks passed +``` + +After merging the current `main` into `flutter/schedule-form` (conflict-free; +the incoming work was unrelated template and chat-composer state changes), the +same checks were re-run on the merged tree: `flutter analyze` clean, 69 schedules +tests, 704 whole-app tests, `flutter build web`, and all six fixture probe checks +with no page errors. + +Browser checks that actually ran in real headless Chrome against the fixture: + +- blank submit: 0 callbacks, both field errors exposed; +- first valid submit: pending state, 1 callback, a second click left the count at + 1; +- refusal: `lastError = conflict: revision 13 is stale`, `records = 0`, name and + prompt still `Probe schedule` / `Summarise the release notes.`, and the visible + line contains `Your draft is preserved.`; +- retry: exactly one accepted record, deep-equal to + `{id:0, name:"Probe schedule", pipeline_id:4, version:2, enabled:true, + input:{prompt:"Summarise the release notes."}, workspace:"/srv/research", + rule:{every:"24h", timezone:"Europe/London"}, notify_mode:"auto"}`; +- 320px at 2x text: labels/helpers and both actions still present and readable; +- Cupertino dark at 390px: native fields, switch, checkboxes and actions rendered. + +Captures (shared artifact): + +``` +/Users/alan/.local/share/pipelines/data/artifacts/78/public/s1-form-captures/ + s1-form-material-390-invalid.png + s1-form-material-390-refusal.png + s1-form-material-390-record.png + s1-form-material-320-2x-top.png + s1-form-material-320-2x-bottom.png + s1-form-cupertino-dark-390-top.png + s1-form-cupertino-dark-390-bottom.png + manifest.json +``` + +The refusal copy is visible in +`s1-form-material-390-refusal.png`; the exact accepted record is visible in +`s1-form-material-390-record.png`; wrapping at 320/2x is visible in the two +`320-2x` captures. + +## Full diff + +Every path is new; no existing file is modified. The reviewed patch is committed +as `feat(app): add native saved-schedule editor form` on +`flutter/schedule-form`, followed by a conflict-free merge of `main`. The +reviewed patch snapshot, taken before these landing-state note edits, is saved +at: + +`/Users/alan/.local/share/pipelines/data/artifacts/78/public/s1-form.diff` + +## Honest limits + +- **Committed but not deployed.** The candidate commit is merged with `main` and + checked on `flutter/schedule-form`; no push, deployment or canonical URL + change was performed by this work. +- **Not wired into the normal Schedules screen or shell.** There is no editor + dialog/route, no `screen.dart` integration and no navigation; the Schedules + destination's editor entry is a later integration slice. +- **No save engine, repository, network, create/update/pause/delete.** The form + only calls its injected callback and never opens a socket. The existing draft + and repository were not changed. +- **Advanced run options stay preserved but are not editable** in this slice + (`model`, stage models, other input keys, write paths, allow tools, title, + output format). No control was invented for them. +- **Timezone validity remains the landed draft's structural check.** The UI only + displays the draft's error; Dart still has no IANA database here. +- **Mobile unverified.** Only web-targeted Flutter tests/analyze/build ran. No + Android/iOS build, emulator, ADB or device was used. +- **Live server unverified.** Browser evidence is fixture-only; no production + authentication, schedule or run was created or changed. +- **Refusal prefix is the caller's error text.** The real `ProtocolError` has a + clean `toString()`; the fixture throws a custom refusal so the capture does not + show Dart's `Bad state:` prefix from `StateError`. diff --git a/app/test/features/schedules/ui/editor/schedule_editor_form_test.dart b/app/test/features/schedules/ui/editor/schedule_editor_form_test.dart new file mode 100644 index 00000000..050b118d --- /dev/null +++ b/app/test/features/schedules/ui/editor/schedule_editor_form_test.dart @@ -0,0 +1,162 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_selectors.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_wording.dart'; + +import 'schedule_editor_harness.dart'; + +void main() { + testWidgets('invalid draft shows field errors and sends nothing', ( + tester, + ) async { + final calls = []; + await pumpScheduleEditor( + tester, + draft: createDraft(), + onSubmit: (record) async => calls.add(record), + ); + expect(find.text('Add schedule'), findsOneWidget); + + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pump(); + + expect(find.text('Enter a schedule name.'), findsOneWidget); + expect(find.text('Enter a prompt.'), findsOneWidget); + expect(calls, isEmpty); + expect( + tester + .widget(find.byKey(scheduleEditorVersionKey)) + .controller! + .text, + '2', + ); + }); + + testWidgets('valid create sends the exact save record', (tester) async { + final calls = []; + final draft = createDraft(); + await pumpScheduleEditor( + tester, + draft: draft, + onSubmit: (record) async => calls.add(record), + ); + + await enterField(tester, scheduleEditorNameKey, 'Probe schedule'); + await enterField( + tester, + scheduleEditorPromptKey, + 'Summarise the release notes.', + ); + await tester.tap(find.byKey(scheduleEditorDayKey('mon'))); + await tester.tap(find.byKey(scheduleEditorDayKey('wed'))); + await tester.pump(); + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pumpAndSettle(); + + expect(calls, hasLength(1)); + expect(calls.single, { + 'id': 0, + 'name': 'Probe schedule', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': {'prompt': 'Summarise the release notes.'}, + 'workspace': '/srv/research', + 'rule': { + 'every': '24h', + 'days': ['mon', 'wed'], + 'timezone': 'Europe/London', + }, + 'notify_mode': 'auto', + }); + expect(calls.single.containsKey('revision'), isFalse); + expect(draft.source, isNull); + }); + + testWidgets('clock times, paused state and notifications reach the record', ( + tester, + ) async { + final calls = []; + await pumpScheduleEditor( + tester, + draft: createDraft(name: 'Clock schedule', prompt: 'Run at times'), + onSubmit: (record) async => calls.add(record), + ); + + await tester.tap(find.byKey(scheduleEditorTimerKey)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Clock times').last); + await tester.pumpAndSettle(); + expect(find.text('Clock times (24h, comma separated)'), findsOneWidget); + expect(find.text('Interval (at least 1m)'), findsNothing); + + await enterField(tester, scheduleEditorTimesKey, '09:00, 17:30'); + await tester.tap(find.byKey(scheduleEditorEnabledKey)); + await tester.tap(find.byKey(scheduleEditorNotifyKey)); + await tester.pumpAndSettle(); + await tester.tap(find.text('off').last); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pumpAndSettle(); + + expect(calls.single['enabled'], isFalse); + expect(calls.single['notify_mode'], 'off'); + expect(calls.single['rule'], { + 'times': ['09:00', '17:30'], + 'timezone': 'Europe/London', + }); + }); + + testWidgets('editing keeps CAS identity and unknown raw fields', ( + tester, + ) async { + final calls = []; + await pumpScheduleEditor( + tester, + draft: editDraft(), + onSubmit: (record) async => calls.add(record), + ); + expect(find.text('Edit schedule'), findsOneWidget); + expect( + tester + .widget(find.byKey(scheduleEditorNameKey)) + .controller! + .text, + 'Saved topic', + ); + + await enterField(tester, scheduleEditorNameKey, 'Edited topic'); + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pumpAndSettle(); + + final record = calls.single; + expect(record['id'], 9); + expect(record['revision'], 13); + expect(record['pipeline_id'], 4); + expect(record['name'], 'Edited topic'); + expect(record['input'], { + 'prompt': 'Topic', + 'count': 4, + 'flag': false, + 'nested': { + 'list': [null, 2], + }, + }); + expect(record['rule'], { + 'times': ['09:00', '17:30'], + 'days': ['fri', 'mon'], + 'future': 'keep', + }); + expect(record['model'], 'provider/model'); + expect(record['stage_models'], {'research': 'provider/other'}); + expect(record['write_paths'], ['src/file.go']); + expect(record['allow_tools'], isTrue); + expect(record['title'], 'Saved title'); + expect(record['output_format'], 'json'); + expect(record['notify_mode'], 'off'); + expect(record['server_extra'], { + 'keep': [1, true], + }); + }); +} diff --git a/app/test/features/schedules/ui/editor/schedule_editor_harness.dart b/app/test/features/schedules/ui/editor/schedule_editor_harness.dart new file mode 100644 index 00000000..71052bc0 --- /dev/null +++ b/app/test/features/schedules/ui/editor/schedule_editor_harness.dart @@ -0,0 +1,82 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/domain/editor/schedule_draft.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_form.dart'; + +import '../../domain/editor/draft_fixtures.dart'; + +ScheduleDraft createDraft({ + String name = '', + String prompt = '', + String version = '2', + String workspace = '/srv/research', + String timezone = 'Europe/London', +}) => + ScheduleDraft.create( + pipelineId: 4, + version: version, + workspace: workspace, + timezone: timezone, + ) + ..name = name + ..prompt = prompt; + +ScheduleDraft editDraft() => + ScheduleDraft.fromSchedule(SavedSchedule(deepCopy(completeRecord()))); + +Future pumpScheduleEditor( + WidgetTester tester, { + required ScheduleDraft draft, + required Future Function(JsonMap record) onSubmit, + bool cupertino = false, + bool dark = false, + double width = 390, + double height = 1600, + double textScale = 1, + VoidCallback? onCancel, +}) async { + tester.view.physicalSize = Size(width, height); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final form = SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: ScheduleEditorForm( + draft: draft, + onSubmit: onSubmit, + onCancel: onCancel, + ), + ); + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + builder: scaled, + home: CupertinoPageScaffold(child: SafeArea(child: form)), + ) + : MaterialApp( + theme: ThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + builder: scaled, + home: Scaffold(body: SafeArea(child: form)), + ), + ); + await tester.pumpAndSettle(); +} + +Future enterField(WidgetTester tester, Key key, String value) async { + await tester.enterText(find.byKey(key), value); + await tester.pump(); +} diff --git a/app/test/features/schedules/ui/editor/schedule_editor_interaction_test.dart b/app/test/features/schedules/ui/editor/schedule_editor_interaction_test.dart new file mode 100644 index 00000000..e56e65f5 --- /dev/null +++ b/app/test/features/schedules/ui/editor/schedule_editor_interaction_test.dart @@ -0,0 +1,164 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_selectors.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_wording.dart'; + +import 'schedule_editor_harness.dart'; + +void main() { + testWidgets('async refusal keeps typed values and a retry can succeed', ( + tester, + ) async { + final calls = []; + Object? refusal = StateError('revision 13 is stale'); + await pumpScheduleEditor( + tester, + draft: createDraft(name: 'Probe schedule', prompt: 'Keep these words'), + onSubmit: (record) async { + calls.add(record); + if (refusal case final error?) throw error; + }, + ); + + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pumpAndSettle(); + expect(find.byKey(scheduleEditorErrorKey), findsOneWidget); + expect(find.textContaining('revision 13 is stale'), findsOneWidget); + expect(find.textContaining('Your draft is preserved.'), findsOneWidget); + expect( + tester + .widget(find.byKey(scheduleEditorNameKey)) + .controller! + .text, + 'Probe schedule', + ); + expect( + tester + .widget(find.byKey(scheduleEditorPromptKey)) + .controller! + .text, + 'Keep these words', + ); + expect( + tester + .widget(find.byKey(scheduleEditorSubmitKey)) + .onPressed, + isNotNull, + ); + + refusal = null; + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pumpAndSettle(); + expect(calls, hasLength(2)); + expect(calls.last['name'], 'Probe schedule'); + expect(find.byKey(scheduleEditorErrorKey), findsNothing); + }); + + testWidgets('a sending form locks controls and rejects a second submit', ( + tester, + ) async { + final gate = Completer(); + var calls = 0; + await pumpScheduleEditor( + tester, + draft: createDraft(name: 'Probe schedule', prompt: 'Run once'), + onSubmit: (_) { + calls++; + return gate.future; + }, + ); + + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pump(); + expect(find.text('Saving…'), findsOneWidget); + expect( + tester + .widget(find.byKey(scheduleEditorSubmitKey)) + .onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(scheduleEditorNameKey)).enabled, + isFalse, + ); + + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pump(); + expect(calls, 1); + + gate.complete(); + await tester.pumpAndSettle(); + expect(find.text('Save schedule'), findsOneWidget); + expect( + tester + .widget(find.byKey(scheduleEditorSubmitKey)) + .onPressed, + isNotNull, + ); + }); + + testWidgets('Cupertino form uses native fields and action sheets', ( + tester, + ) async { + final calls = []; + await pumpScheduleEditor( + tester, + cupertino: true, + draft: createDraft(name: 'Cupertino schedule', prompt: 'Native fields'), + onSubmit: (record) async => calls.add(record), + ); + expect(find.byType(CupertinoTextField), findsNWidgets(6)); + expect(find.byType(TextField), findsNothing); + expect(find.byType(CupertinoSwitch), findsOneWidget); + expect(find.byType(Switch), findsNothing); + expect(find.byType(CupertinoCheckbox), findsNWidgets(7)); + expect(find.byType(Checkbox), findsNothing); + + await tester.tap(find.byKey(scheduleEditorTimerKey)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Clock times').last); + await tester.pumpAndSettle(); + await enterField(tester, scheduleEditorTimesKey, '06:30'); + await tester.tap(find.byKey(scheduleEditorDayKey('mon'))); + await tester.pump(); + expect( + tester + .widget(find.byKey(scheduleEditorDayKey('mon'))) + .value, + isTrue, + ); + await tester.tap(find.byKey(scheduleEditorEnabledKey)); + await tester.pump(); + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pumpAndSettle(); + + expect(calls.single['enabled'], isFalse); + expect(calls.single['rule'], { + 'times': ['06:30'], + 'days': ['mon'], + 'timezone': 'Europe/London', + }); + }); + + testWidgets('Cancel calls the injected callback and sends nothing', ( + tester, + ) async { + var cancelled = 0; + final calls = []; + await pumpScheduleEditor( + tester, + draft: createDraft(name: 'Probe schedule', prompt: 'Prompt'), + onSubmit: (record) async => calls.add(record), + onCancel: () => cancelled++, + ); + + await tester.tap(find.byKey(scheduleEditorCancelKey)); + await tester.pump(); + expect(cancelled, 1); + expect(calls, isEmpty); + }); +} diff --git a/app/test/features/schedules/ui/editor/schedule_editor_layout_test.dart b/app/test/features/schedules/ui/editor/schedule_editor_layout_test.dart new file mode 100644 index 00000000..55613296 --- /dev/null +++ b/app/test/features/schedules/ui/editor/schedule_editor_layout_test.dart @@ -0,0 +1,80 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_wording.dart'; + +import 'schedule_editor_harness.dart'; + +const _labels = [ + scheduleEditorNameLabel, + scheduleEditorPromptLabel, + scheduleEditorVersionLabel, + scheduleEditorWorkspaceLabel, + scheduleEditorTimerLabel, + scheduleEditorEveryLabel, + scheduleEditorDaysLabel, + scheduleEditorTimezoneLabel, + scheduleEditorEnabledLabel, + scheduleEditorEnabledNote, + scheduleEditorNotificationsLabel, + scheduleEditorSubmitLabel, +]; + +void main() { + testWidgets('Material labels wrap at 320px with 2x text', (tester) async { + await pumpScheduleEditor( + tester, + width: 320, + height: 1800, + textScale: 2, + draft: createDraft(), + onSubmit: (JsonMap record) async {}, + ); + expect(tester.takeException(), isNull); + for (final label in _labels) { + expect(find.text(label), findsOneWidget, reason: label); + } + expect(find.byType(TextField), findsNWidgets(6)); + expect(find.byType(Switch), findsOneWidget); + expect(find.byType(Checkbox), findsNWidgets(7)); + final note = tester.renderObject( + find.text(scheduleEditorEnabledNote), + ); + expect(note.size.width, lessThanOrEqualTo(320 - 32)); + }); + + testWidgets('Cupertino dark uses native controls and the native palette', ( + tester, + ) async { + await pumpScheduleEditor( + tester, + cupertino: true, + dark: true, + width: 320, + height: 1800, + textScale: 2, + draft: createDraft(), + onSubmit: (JsonMap record) async {}, + ); + expect(tester.takeException(), isNull); + for (final label in _labels) { + expect(find.text(label), findsOneWidget, reason: label); + } + expect(find.byType(CupertinoTextField), findsNWidgets(6)); + expect(find.byType(CupertinoSwitch), findsOneWidget); + expect(find.byType(CupertinoCheckbox), findsNWidgets(7)); + expect(find.byType(Material), findsNothing); + expect(find.byType(TextField), findsNothing); + expect(find.byType(Switch), findsNothing); + expect(find.byType(Checkbox), findsNothing); + + final context = tester.element(find.byKey(scheduleEditorNameKey)); + expect(CupertinoTheme.of(context).brightness, Brightness.dark); + expect( + CupertinoColors.label.resolveFrom(context).toARGB32(), + CupertinoColors.label.darkColor.toARGB32(), + ); + }); +} diff --git a/app/tool/schedule_editor_probe.mjs b/app/tool/schedule_editor_probe.mjs new file mode 100644 index 00000000..941d253a --- /dev/null +++ b/app/tool/schedule_editor_probe.mjs @@ -0,0 +1,368 @@ +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 native saved-schedule form. +// +// flutter build web -t tool/schedule_editor_probe_app.dart \ +// -o build/schedule_editor_probe_web +// OPENCODE_ARTIFACT_DIR= node tool/schedule_editor_probe.mjs +// +// The fixture callback and record are in-process; no Pipelines server, +// authentication or real schedule is contacted. + +const root = resolve(process.env.PROBE_WEB_ROOT ?? 'build/schedule_editor_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', + '.otf': 'font/otf', + '.ttf': 'font/ttf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.ico': 'image/x-icon', + '.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-form-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('flt-semantics')) { + const label = el.getAttribute('aria-label'); + if (label) chunks.push(label); + 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, 3000)}`); + } + }; + + const click = async (needle, optional = false) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(needle)}; + const nodes = [...document.querySelectorAll('flt-semantics')]; + const node = nodes.find((x) => (x.getAttribute('aria-label') || '').trim() === wanted) + || nodes.find((x) => (x.innerText || '').trim() === wanted) + || nodes.find((x) => (x.getAttribute('aria-label') || x.innerText || '').trim().startsWith(wanted)); + if (!node) return false; + node.click(); + return true; + })()`); + if (!clicked && !optional) { + throw new Error(`Could not click ${JSON.stringify(needle)}\n${(await text()).slice(0, 3000)}`); + } + await delay(350); + 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, 3000)}`); + await delay(250); + await send('Input.insertText', { text: value }, session); + await delay(350); + }; + + const state = () => evaluate('globalThis.scheduleEditorProbe ?? 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(400); + }; + 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(1200); + await assertText('Add schedule'); + }; + + const checks = []; + const captures = []; + + // Material phone: invalid -> valid -> refusal -> exact record. + await load('host=material&scale=1', 390, 844); + await assertText('Future runs only; does not publish or change the workflow.'); + await assertText('Weekdays (none means every day)'); + await assertText('Enabled schedules start future runs automatically'); + await click('Save schedule'); + await delay(500); + let current = await state(); + let fields = await inputs(); + const nameField = fields.find((field) => field.label.startsWith('Name')); + const promptField = fields.find((field) => field.label.startsWith('Prompt')); + if (current?.submits !== 0) throw new Error(`Invalid form submitted: ${JSON.stringify(current)}`); + if (!nameField?.label.includes('Enter a schedule name.')) { + throw new Error(`Name error missing: ${JSON.stringify(fields)}`); + } + if (!promptField?.label.includes('Enter a prompt.')) { + throw new Error(`Prompt error missing: ${JSON.stringify(fields)}`); + } + await capture('s1-form-material-390-invalid'); + checks.push({ + check: 'invalid submit showed both field errors and sent nothing', + submits: current.submits, + fields, + }); + + await typeField('Name', 'Probe schedule'); + await typeField('Prompt', 'Summarise the release notes.'); + await click('Save schedule'); + await delay(200); + current = await state(); + if (current?.pending !== true || current?.submits !== 1) { + throw new Error(`First submit did not enter the sending state: ${JSON.stringify(current)}`); + } + await click('Saving…', true); + await delay(150); + current = await state(); + if (current?.submits !== 1) { + throw new Error(`A second submit escaped while sending: ${JSON.stringify(current)}`); + } + checks.push({ check: 'sending disabled a duplicate submit', submits: current.submits }); + + await delay(1100); + current = await state(); + fields = await inputs(); + if (current?.pending !== false || current?.records !== 0) { + throw new Error(`Refusal state drifted: ${JSON.stringify(current)}`); + } + if (current?.lastError !== 'conflict: revision 13 is stale') { + throw new Error(`Refusal was not the fixture's: ${JSON.stringify(current)}`); + } + if ( + fields.find((field) => field.label.startsWith('Name'))?.value !== 'Probe schedule' + || fields.find((field) => field.label.startsWith('Prompt'))?.value + !== 'Summarise the release notes.' + ) { + throw new Error(`Refusal lost typed values: ${JSON.stringify(fields)}`); + } + await wheel(900); + await assertText('Your draft is preserved.'); + await capture('s1-form-material-390-refusal'); + checks.push({ + check: 'refusal kept both typed values, showed the preservation copy and re-enabled the form', + lastError: current.lastError, + refusalCopy: 'Your draft is preserved.', + values: fields.map((field) => [field.label.split('\n')[0], field.value]), + }); + + await click('Save schedule'); + await waitFor(async () => (await state())?.records === 1, 'the accepted record'); + current = await state(); + deepStrictEqual(current.lastRecord, { + id: 0, + name: 'Probe schedule', + pipeline_id: 4, + version: 2, + enabled: true, + input: { prompt: 'Summarise the release notes.' }, + workspace: '/srv/research', + rule: { every: '24h', timezone: 'Europe/London' }, + notify_mode: 'auto', + }); + await delay(500); + await wheel(1400); + await capture('s1-form-material-390-record'); + checks.push({ + check: 'retry submitted the exact create record once', + submits: current.submits, + records: current.records, + record: current.lastRecord, + }); + + // Narrow phone at 2x text: labels and helpers wrap, nothing overflows. + await load('host=material&scale=2', 320, 844); + await click('Save schedule'); + await delay(600); + await capture('s1-form-material-320-2x-top'); + for (let i = 0; i < 5; i++) await wheel(600); + await capture('s1-form-material-320-2x-bottom'); + await assertText('Enabled schedules start future runs automatically'); + await assertText('Save schedule'); + checks.push({ check: '320px at 2x text kept every label and the actions', width: 320, scale: 2 }); + + // Actual Cupertino dark host, not a Material fallback. + await load('host=cupertino&brightness=dark&scale=1', 390, 844); + await assertText('Add schedule'); + await capture('s1-form-cupertino-dark-390-top'); + for (let i = 0; i < 3; i++) await wheel(600); + await capture('s1-form-cupertino-dark-390-bottom'); + await assertText('Notifications'); + checks.push({ check: 'Cupertino dark rendered the native form', host: 'cupertino', brightness: 'dark' }); + + if (pageErrors.length) throw new Error(`Page exceptions: ${JSON.stringify(pageErrors)}`); + const manifest = { + url: origin, + fixture: 'tool/schedule_editor_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_editor_probe_app.dart b/app/tool/schedule_editor_probe_app.dart new file mode 100644 index 00000000..d65c1db8 --- /dev/null +++ b/app/tool/schedule_editor_probe_app.dart @@ -0,0 +1,170 @@ +import 'dart:convert'; +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/domain/editor/schedule_draft.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_form.dart'; + +/// Isolated browser fixture for the native saved-schedule form. +/// +/// flutter build web -t tool/schedule_editor_probe_app.dart +/// +/// Query: `host=cupertino`, `brightness=dark`, `scale=2`. The injected callback +/// refuses the first valid submit and accepts the retry; it never opens a +/// socket or touches a real schedule. Its counters/record are published at +/// `globalThis.scheduleEditorProbe` for the Chrome probe. +void main() => runApp(const _ProbeApp()); + +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 home = _ProbeHome(cupertino: cupertino); + if (cupertino) { + return CupertinoApp( + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + builder: media, + home: CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar( + middle: Text('Schedule editor probe'), + ), + child: SafeArea(child: home), + ), + ); + } + return MaterialApp( + theme: ThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + platform: TargetPlatform.android, + ), + builder: media, + home: Scaffold( + appBar: AppBar(title: const Text('Schedule editor probe')), + body: SafeArea(child: home), + ), + ); + } +} + +class _Refusal implements Exception { + const _Refusal(); + + @override + String toString() => 'conflict: revision 13 is stale'; +} + +class _ProbeHome extends StatefulWidget { + const _ProbeHome({required this.cupertino}); + + final bool cupertino; + + @override + State<_ProbeHome> createState() => _ProbeHomeState(); +} + +class _ProbeHomeState extends State<_ProbeHome> { + final _draft = ScheduleDraft.create( + pipelineId: 4, + version: '2', + workspace: '/srv/research', + timezone: 'Europe/London', + ); + int _submits = 0; + int _records = 0; + bool _pending = false; + bool _refuseNext = true; + String? _lastError; + JsonMap? _lastRecord; + + @override + void initState() { + super.initState(); + _publish(); + } + + void _publish() { + globalContext.setProperty( + 'scheduleEditorProbe'.toJS, + { + 'submits': _submits, + 'records': _records, + 'pending': _pending, + 'lastError': _lastError, + 'lastRecord': _lastRecord, + }.jsify(), + ); + } + + Future _submit(JsonMap record) async { + _submits++; + _pending = true; + _publish(); + if (mounted) setState(() {}); + await Future.delayed(const Duration(milliseconds: 900)); + if (_refuseNext) { + _refuseNext = false; + _pending = false; + _lastError = 'conflict: revision 13 is stale'; + _publish(); + if (mounted) setState(() {}); + throw const _Refusal(); + } + _pending = false; + _records++; + _lastRecord = record; + _publish(); + if (mounted) setState(() {}); + } + + @override + Widget build(BuildContext context) { + final record = _lastRecord; + return SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 640), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ScheduleEditorForm( + draft: _draft, + onSubmit: _submit, + onCancel: () {}, + ), + if (record != null) ...[ + const SizedBox(height: 24), + Text( + 'Submitted record', + style: widget.cupertino + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 8), + SelectableText( + const JsonEncoder.withIndent(' ').convert(record), + ), + ], + ], + ), + ), + ), + ); + } +}