From 8760a01b175e75c07d84b7c62d4367fab735db5d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:51:15 +0100 Subject: [PATCH 01/17] feat(app): add native saved-schedule editor form --- .../ui/editor/schedule_editor_fields.dart | 191 +++++++++ .../ui/editor/schedule_editor_form.dart | 234 +++++++++++ .../ui/editor/schedule_editor_form_body.dart | 229 +++++++++++ .../ui/editor/schedule_editor_selectors.dart | 200 ++++++++++ .../ui/editor/schedule_editor_wording.dart | 45 +++ app/notes/S1-form.md | 176 +++++++++ .../ui/editor/schedule_editor_form_test.dart | 162 ++++++++ .../ui/editor/schedule_editor_harness.dart | 82 ++++ .../schedule_editor_interaction_test.dart | 164 ++++++++ .../editor/schedule_editor_layout_test.dart | 80 ++++ app/tool/schedule_editor_probe.mjs | 368 ++++++++++++++++++ app/tool/schedule_editor_probe_app.dart | 170 ++++++++ 12 files changed, 2101 insertions(+) create mode 100644 app/lib/features/schedules/ui/editor/schedule_editor_fields.dart create mode 100644 app/lib/features/schedules/ui/editor/schedule_editor_form.dart create mode 100644 app/lib/features/schedules/ui/editor/schedule_editor_form_body.dart create mode 100644 app/lib/features/schedules/ui/editor/schedule_editor_selectors.dart create mode 100644 app/lib/features/schedules/ui/editor/schedule_editor_wording.dart create mode 100644 app/notes/S1-form.md create mode 100644 app/test/features/schedules/ui/editor/schedule_editor_form_test.dart create mode 100644 app/test/features/schedules/ui/editor/schedule_editor_harness.dart create mode 100644 app/test/features/schedules/ui/editor/schedule_editor_interaction_test.dart create mode 100644 app/test/features/schedules/ui/editor/schedule_editor_layout_test.dart create mode 100644 app/tool/schedule_editor_probe.mjs create mode 100644 app/tool/schedule_editor_probe_app.dart 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..07dd36dd --- /dev/null +++ b/app/notes/S1-form.md @@ -0,0 +1,176 @@ +# 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 passed +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 +``` + +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 and currently untracked; `git status --short` lists only those +paths and no existing file is modified. The complete patch is saved at: + +`/Users/alan/.local/share/pipelines/data/artifacts/78/public/s1-form.diff` + +## Honest limits + +- **Not committed, pushed or deployed.** This stage forbids that. The candidate + is in the `flutter/schedule-form` worktree for the manager. +- **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), + ), + ], + ], + ), + ), + ), + ); + } +} From 475e1ae5081d4158a4ccf58bf23e370e598ef431 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:53:55 +0100 Subject: [PATCH 02/17] docs(app): record landed state for the schedule editor form --- app/notes/S1-form.md | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/app/notes/S1-form.md b/app/notes/S1-form.md index 07dd36dd..db4bccd6 100644 --- a/app/notes/S1-form.md +++ b/app/notes/S1-form.md @@ -102,7 +102,8 @@ 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 passed +flutter test # 686 passed before the + # main merge, 687 after flutter build web # ✓ Built build/web flutter build web -t tool/schedule_editor_probe_app.dart \ -o build/schedule_editor_probe_web # ✓ Built @@ -111,6 +112,11 @@ OPENCODE_ARTIFACT_DIR=…/78/public/s1-form-captures \ node tool/schedule_editor_probe.mjs # all checks passed ``` +After merging `main` into `flutter/schedule-form` (conflict-free; the incoming +commit only touches templates), the same checks were re-run on the merged tree: +`flutter analyze` clean, 69 schedules tests, 687 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; @@ -147,15 +153,18 @@ The refusal copy is visible in ## Full diff -Every path is new and currently untracked; `git status --short` lists only those -paths and no existing file is modified. The complete patch is saved at: +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 +complete patch is also saved at: `/Users/alan/.local/share/pipelines/data/artifacts/78/public/s1-form.diff` ## Honest limits -- **Not committed, pushed or deployed.** This stage forbids that. The candidate - is in the `flutter/schedule-form` worktree for the manager. +- **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. From f9db64a916e1749cf8f120523cef82baf45566fe Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:56:41 +0100 Subject: [PATCH 03/17] docs(app): record merged schedule form checks --- app/notes/S1-form.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/app/notes/S1-form.md b/app/notes/S1-form.md index db4bccd6..6ed7eafa 100644 --- a/app/notes/S1-form.md +++ b/app/notes/S1-form.md @@ -102,8 +102,8 @@ 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 passed before the - # main merge, 687 after +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 @@ -112,10 +112,11 @@ OPENCODE_ARTIFACT_DIR=…/78/public/s1-form-captures \ node tool/schedule_editor_probe.mjs # all checks passed ``` -After merging `main` into `flutter/schedule-form` (conflict-free; the incoming -commit only touches templates), the same checks were re-run on the merged tree: -`flutter analyze` clean, 69 schedules tests, 687 whole-app tests, `flutter build -web`, and all six fixture probe checks with no page errors. +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: From ca9e42e08032493f6897e3220532ae0ce79cecc5 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:57:03 +0100 Subject: [PATCH 04/17] docs(app): clarify reviewed patch snapshot in schedule form notes --- app/notes/S1-form.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/notes/S1-form.md b/app/notes/S1-form.md index 6ed7eafa..ac572fbc 100644 --- a/app/notes/S1-form.md +++ b/app/notes/S1-form.md @@ -157,7 +157,8 @@ The refusal copy is visible in 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 -complete patch is also saved at: +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` From 6a0f1c345e628883d5dc27fca5f61d5a177c8741 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:00:07 +0100 Subject: [PATCH 05/17] docs(app): record schedule form acceptance evidence --- app/notes/S1-form.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/app/notes/S1-form.md b/app/notes/S1-form.md index ac572fbc..1edfd633 100644 --- a/app/notes/S1-form.md +++ b/app/notes/S1-form.md @@ -1,5 +1,14 @@ # S1-form — native saved-schedule form +Manager acceptance: merged after inspecting the new-source-only diff. Re-ran all +schedule tests and rebuilt the fixture; the probe passed every step and produced +seven captures. Inspected the Cupertino dark phone form and the 320px/2x Material +form: full wrapping labels, native fields/menus/switches, readable semantic error +colour, no clipped helper copy. The form mutates only the caller-owned draft and +calls the injected submit callback, so no repository/route/scheduler is implied. +Schedule persistence, pause/delete, conflicts and the Schedule-this-run seed are +still separate wiring work; nothing was saved to a real server. + ## What changed New files only. No existing feature, shell, route, `main`, pubspec, server, `web/`, From c56b5d45a4816913e27fa831dad404dfd2249c65 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:03:55 +0100 Subject: [PATCH 06/17] feat(app): add native template gallery with detail and create --- app/lib/features/templates/screen.dart | 208 ++++++++++ .../templates/ui/template_detail.dart | 168 ++++++++ .../templates/ui/template_gallery.dart | 138 +++++++ .../templates/ui/templates_failure.dart | 118 ++++++ .../templates/ui/templates_frame.dart | 104 +++++ app/notes/T1-gallery.md | 175 ++++++++ .../ui/template_gallery_create_test.dart | 104 +++++ .../ui/template_gallery_screen_test.dart | 379 +++++++++++++++++ .../ui/template_gallery_test_support.dart | 112 +++++ app/tool/templates_gallery_probe.dart | 178 ++++++++ app/tool/templates_gallery_probe.mjs | 386 ++++++++++++++++++ 11 files changed, 2070 insertions(+) create mode 100644 app/lib/features/templates/screen.dart create mode 100644 app/lib/features/templates/ui/template_detail.dart create mode 100644 app/lib/features/templates/ui/template_gallery.dart create mode 100644 app/lib/features/templates/ui/templates_failure.dart create mode 100644 app/lib/features/templates/ui/templates_frame.dart create mode 100644 app/notes/T1-gallery.md create mode 100644 app/test/features/templates/ui/template_gallery_create_test.dart create mode 100644 app/test/features/templates/ui/template_gallery_screen_test.dart create mode 100644 app/test/features/templates/ui/template_gallery_test_support.dart create mode 100644 app/tool/templates_gallery_probe.dart create mode 100644 app/tool/templates_gallery_probe.mjs diff --git a/app/lib/features/templates/screen.dart b/app/lib/features/templates/screen.dart new file mode 100644 index 00000000..20bc130d --- /dev/null +++ b/app/lib/features/templates/screen.dart @@ -0,0 +1,208 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../../core/api_gateway.dart'; +import '../../ui/adaptive/host.dart'; +import 'data/template_repository.dart'; +import 'domain/template_entry.dart'; +import 'ui/template_create_dialog.dart'; +import 'ui/template_detail.dart'; +import 'ui/template_gallery.dart'; +import 'ui/templates_failure.dart'; +import 'ui/templates_frame.dart'; + +export 'ui/template_detail.dart' + show + templateCreateActionKey, + templateDetailKey, + templateSourceKey, + templateSourceLabel; +export 'ui/template_gallery.dart' + show + templateRowKey, + templatesEmptyKey, + templatesGalleryKey, + templatesLoadingKey; +export 'ui/templates_failure.dart' + show + templatesBannerRetryKey, + templatesErrorBannerKey, + templatesErrorKey, + templatesRetryKey; +export 'ui/templates_frame.dart' show templatesBackKey, templatesRefreshKey; + +/// The reusable Templates gallery: the server's actual catalogue, one selected +/// template's metadata and verbatim selectable source, and the existing native +/// create-only prompt. +/// +/// Loading and selecting only read. The single create action calls +/// [showTemplateCreateDialog] unchanged, so validate-then-submit semantics stay +/// there; an accepted `detail` is forwarded once through [onCreated]. Nothing +/// here publishes, runs, schedules or overwrites a pipeline. +/// +/// Standalone use keeps this screen's own native app bar with Back and Refresh. +/// A shell that already owns navigation passes [embedded], which drops the bar +/// and keeps Back inside the detail and Refresh at the top of the body. +class TemplatesScreen extends StatefulWidget { + const TemplatesScreen({ + super.key, + required this.gateway, + this.embedded = false, + this.onCreated, + }); + + final ApiGateway gateway; + final bool embedded; + final ValueChanged? onCreated; + + @override + State createState() => _TemplatesScreenState(); +} + +class _TemplatesScreenState extends State { + late TemplateRepository _repository = TemplateRepository(widget.gateway); + List _templates = const []; + bool _loading = true; + bool _loaded = false; + String? _error; + String? _selectedKey; + int _generation = 0; + + @override + void initState() { + super.initState(); + unawaited(_load()); + } + + @override + void didUpdateWidget(TemplatesScreen oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.gateway == widget.gateway) return; + // A different gateway is a different server: never keep this one's rows or + // selection while the replacement is read. + _repository = TemplateRepository(widget.gateway); + _templates = const []; + _loaded = false; + _selectedKey = null; + unawaited(_load()); + } + + bool _owns(int generation) => mounted && generation == _generation; + + Future _load() async { + final generation = ++_generation; + setState(() { + _loading = true; + _error = null; + }); + try { + final templates = await _repository.listTemplates(); + if (!_owns(generation)) return; + setState(() { + _templates = templates; + _loaded = true; + _loading = false; + final selected = _selectedKey; + if (selected != null && + !templates.any((entry) => entry.key == selected)) { + _selectedKey = null; + } + }); + } catch (error) { + if (!_owns(generation)) return; + setState(() { + _loading = false; + _error = _describe(error); + }); + } + } + + String _describe(Object error) { + final text = error is TemplateRepositoryException + ? error.message + : '$error'; + final message = text.trim(); + if (message.isEmpty) return 'The templates could not be loaded.'; + return message.startsWith('Exception: ') ? message.substring(11) : message; + } + + TemplateEntry? get _selected { + for (final entry in _templates) { + if (entry.key == _selectedKey) return entry; + } + return null; + } + + void _open(String key) => setState(() => _selectedKey = key); + + void _back() => setState(() => _selectedKey = null); + + void _openCreate(TemplateEntry template) { + unawaited( + showTemplateCreateDialog( + context: context, + template: template, + repository: _repository, + cupertino: usesCupertinoHost(context), + onCreated: (detail) => widget.onCreated?.call(detail), + ), + ); + } + + @override + Widget build(BuildContext context) { + final selected = _selected; + final body = selected == null + ? TemplateGallery( + templates: _templates, + loaded: _loaded, + loading: _loading, + error: _error, + onRetry: () => unawaited(_load()), + onOpen: _open, + ) + : TemplateDetail( + entry: selected, + showBack: widget.embedded, + onBack: _back, + onCreate: () => _openCreate(selected), + ); + final framed = TemplatesFrame( + body: _withFailure(context, body), + embedded: widget.embedded, + canGoBack: selected != null, + refreshing: _loading, + onBack: _back, + onRefresh: () => unawaited(_load()), + ); + if (widget.embedded) return framed; + // A selected template is this screen's own page: native back returns to + // the gallery instead of leaving the destination. + return PopScope( + canPop: selected == null, + onPopInvokedWithResult: (didPop, _) { + if (!didPop && _selectedKey != null) _back(); + }, + child: framed, + ); + } + + /// A refused refresh stays visible above whichever body is current, so an + /// open template never hides a failed read. The rows and selection are kept. + Widget _withFailure(BuildContext context, Widget body) { + final error = _error; + if (error == null || !_loaded) return body; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + TemplatesFailureBanner( + message: error, + retrying: _loading, + onRetry: () => unawaited(_load()), + ), + Expanded(child: body), + ], + ); + } +} diff --git a/app/lib/features/templates/ui/template_detail.dart b/app/lib/features/templates/ui/template_detail.dart new file mode 100644 index 00000000..97c4b204 --- /dev/null +++ b/app/lib/features/templates/ui/template_detail.dart @@ -0,0 +1,168 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/template_entry.dart'; + +/// Browser wording for the gallery and the selected template, kept verbatim. +const templateSourceLabel = 'Definition source'; +const templateIncludesScheduleLabel = 'Includes a schedule'; +const templateCreateActionLabel = 'Create pipeline from this template'; + +const templateDetailKey = ValueKey('template-detail'); +const templateSourceKey = ValueKey('template-source'); +const templateCreateActionKey = ValueKey('template-create-action'); +const templateDetailBackKey = ValueKey('template-detail-back'); + +/// A gallery card's name: a blank name is the explicit unnamed placeholder. +String templateGalleryName(TemplateEntry entry) { + final name = entry.name.trim(); + return name.isEmpty ? '(unnamed template)' : entry.name; +} + +/// A detail's heading: a blank name falls back to the template's key. +String templateDetailName(TemplateEntry entry) { + final name = entry.name.trim(); + return name.isEmpty ? entry.key : entry.name; +} + +/// One template's metadata and its complete, selectable definition source. +/// +/// Selecting and reading a template sends nothing. The one action opens the +/// existing create-only prompt through [onCreate]; this view never submits, +/// runs or schedules anything itself. +class TemplateDetail extends StatelessWidget { + const TemplateDetail({ + super.key, + required this.entry, + required this.showBack, + required this.onBack, + required this.onCreate, + }); + + final TemplateEntry entry; + + /// True under a shell/app bar that does not own a back control for this page. + final bool showBack; + final VoidCallback onBack; + final VoidCallback onCreate; + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + return ListView( + key: templateDetailKey, + padding: const EdgeInsets.only(bottom: 24), + children: [ + if (showBack) _backRow(context, cupertino), + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _createButton(context, cupertino), + const SizedBox(height: 12), + Text( + templateDetailName(entry), + style: templateTitleStyle(context), + ), + if (entry.description.trim().isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(entry.description), + ), + const SizedBox(height: 16), + Text('Key', style: templateMutedStyle(context)), + SelectableText(entry.key, style: templateBodyStyle(context)), + if (entry.scheduled) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(templateIncludesScheduleLabel), + ), + const SizedBox(height: 20), + Text(templateSourceLabel, style: templateSectionStyle(context)), + const SizedBox(height: 8), + // The server's source, byte-for-byte: no trim, re-indent or + // re-encoding, so selecting it copies exactly what was received. + SelectableText( + entry.source, + key: templateSourceKey, + style: templateBodyStyle(context), + ), + ], + ), + ), + ], + ); + } + + Widget _createButton(BuildContext context, bool cupertino) { + if (cupertino) { + return CupertinoButton.filled( + key: templateCreateActionKey, + onPressed: onCreate, + child: const Text(templateCreateActionLabel), + ); + } + return FilledButton( + key: templateCreateActionKey, + onPressed: onCreate, + child: const Text(templateCreateActionLabel), + ); + } + + Widget _backRow(BuildContext context, bool cupertino) { + final back = cupertino + ? CupertinoButton( + key: templateDetailBackKey, + padding: EdgeInsets.zero, + onPressed: onBack, + child: const Icon(CupertinoIcons.back, semanticLabel: 'Back'), + ) + : BackButton(key: templateDetailBackKey, onPressed: onBack); + return Padding( + padding: const EdgeInsets.fromLTRB(4, 4, 16, 0), + child: Row( + children: [ + back, + const SizedBox(width: 4), + Expanded( + child: Text('Templates', style: templateSectionStyle(context)), + ), + ], + ), + ); + } +} + +TextStyle? templateTitleStyle(BuildContext context) => + usesCupertinoHost(context) + ? CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle + : Theme.of(context).textTheme.headlineSmall; + +TextStyle? templateSectionStyle(BuildContext context) => + usesCupertinoHost(context) + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleMedium; + +TextStyle? templateBodyStyle(BuildContext context) { + if (usesCupertinoHost(context)) { + // SelectableText needs an explicit baseline when it inherits no style. + return CupertinoTheme.of( + context, + ).textTheme.textStyle.copyWith(inherit: true); + } + return Theme.of(context).textTheme.bodyMedium; +} + +TextStyle? templateMutedStyle(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, + ); +} diff --git a/app/lib/features/templates/ui/template_gallery.dart b/app/lib/features/templates/ui/template_gallery.dart new file mode 100644 index 00000000..809b0496 --- /dev/null +++ b/app/lib/features/templates/ui/template_gallery.dart @@ -0,0 +1,138 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/template_entry.dart'; +import 'template_detail.dart'; +import 'templates_failure.dart'; + +const templatesGalleryKey = ValueKey('template-gallery'); +const templatesLoadingKey = ValueKey('templates-loading'); +const templatesEmptyKey = ValueKey('templates-empty'); + +const _loadingLabel = 'Loading templates'; +const _loadingMessage = 'Loading templates…'; +const _emptyMessage = 'No templates are available on this server.'; + +Key templateRowKey(String key) => ValueKey('template-row-$key'); + +/// The gallery's truthful states and native catalogue rows. +/// +/// It owns no requests: loading, failure and the actual rows all come from the +/// screen, so opening a row only selects an already-read template. +class TemplateGallery extends StatelessWidget { + const TemplateGallery({ + super.key, + required this.templates, + required this.loaded, + required this.loading, + required this.error, + required this.onRetry, + required this.onOpen, + }); + + final List templates; + final bool loaded; + final bool loading; + final String? error; + final VoidCallback onRetry; + final ValueChanged onOpen; + + @override + Widget build(BuildContext context) => _body(context); + + Widget _body(BuildContext context) { + if (!loaded) { + if (error != null) { + return TemplatesFailureState( + message: error!, + retrying: loading, + onRetry: onRetry, + ); + } + return _loadingState(context); + } + if (templates.isEmpty) return _emptyState(context); + return usesCupertinoHost(context) + ? _cupertinoList(context) + : _materialList(context); + } + + Widget _loadingState(BuildContext context) { + return Center( + key: templatesLoadingKey, + child: Semantics( + liveRegion: true, + label: _loadingLabel, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + usesCupertinoHost(context) + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + const SizedBox(height: 12), + const Text(_loadingMessage), + ], + ), + ), + ); + } + + Widget _emptyState(BuildContext context) { + return Center( + key: templatesEmptyKey, + child: Padding( + padding: const EdgeInsets.all(24), + child: Text(_emptyMessage, style: templateMutedStyle(context)), + ), + ); + } + + Widget _materialList(BuildContext context) { + return ListView.separated( + key: templatesGalleryKey, + itemCount: templates.length, + separatorBuilder: (_, _) => const Divider(height: 1), + itemBuilder: (context, index) { + final entry = templates[index]; + return ListTile( + key: templateRowKey(entry.key), + title: Text(templateGalleryName(entry)), + subtitle: entry.description.trim().isEmpty + ? null + : Text(entry.description), + trailing: const Icon(Icons.chevron_right), + onTap: () => onOpen(entry.key), + ); + }, + ); + } + + Widget _cupertinoList(BuildContext context) { + return ListView( + key: templatesGalleryKey, + children: [ + CupertinoListSection.insetGrouped( + children: [ + for (final entry in templates) + CupertinoListTile( + key: templateRowKey(entry.key), + title: _cupertinoText(templateGalleryName(entry)), + subtitle: entry.description.trim().isEmpty + ? null + : _cupertinoText(entry.description), + trailing: const CupertinoListTileChevron(), + onTap: () => onOpen(entry.key), + ), + ], + ), + ], + ); + } + + /// The native tile is single-line by default. Let its content wrap at larger + /// text sizes instead of ellipsizing a template's own name; the row grows + /// with the content and nothing else about the tile is restyled. + Widget _cupertinoText(String text) => + DefaultTextStyle.merge(maxLines: 3, child: Text(text)); +} diff --git a/app/lib/features/templates/ui/templates_failure.dart b/app/lib/features/templates/ui/templates_failure.dart new file mode 100644 index 00000000..5eab12d8 --- /dev/null +++ b/app/lib/features/templates/ui/templates_failure.dart @@ -0,0 +1,118 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; + +const templatesErrorKey = ValueKey('templates-error'); +const templatesRetryKey = ValueKey('templates-retry'); +const templatesErrorBannerKey = ValueKey('templates-error-banner'); +const templatesBannerRetryKey = ValueKey('templates-banner-retry'); + +/// A refusal for a catalogue that never loaded: the whole body is the failure. +class TemplatesFailureState extends StatelessWidget { + const TemplatesFailureState({ + super.key, + required this.message, + required this.retrying, + required this.onRetry, + }); + + final String message; + final bool retrying; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Center( + key: templatesErrorKey, + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Semantics( + liveRegion: true, + child: Text(message, textAlign: TextAlign.center), + ), + const SizedBox(height: 8), + _retryButton( + context, + buttonKey: templatesRetryKey, + retrying: retrying, + onRetry: onRetry, + ), + ], + ), + ), + ); + } +} + +/// A refused refresh, shown above whichever body stays visible. +/// +/// The screen renders this above both the catalogue and an open template, so a +/// failed refresh can never be silent while a template is selected. +class TemplatesFailureBanner extends StatelessWidget { + const TemplatesFailureBanner({ + super.key, + required this.message, + required this.retrying, + required this.onRetry, + }); + + final String message; + final bool retrying; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Padding( + key: templatesErrorBannerKey, + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Semantics( + liveRegion: true, + child: Text( + message, + style: TextStyle( + color: usesCupertinoHost(context) + ? CupertinoColors.systemRed.resolveFrom(context) + : Theme.of(context).colorScheme.error, + ), + ), + ), + _retryButton( + context, + buttonKey: templatesBannerRetryKey, + retrying: retrying, + onRetry: onRetry, + ), + ], + ), + ); + } +} + +Widget _retryButton( + BuildContext context, { + required Key buttonKey, + required bool retrying, + required VoidCallback onRetry, +}) { + final onPressed = retrying ? null : onRetry; + if (usesCupertinoHost(context)) { + return CupertinoButton( + key: buttonKey, + padding: EdgeInsets.zero, + onPressed: onPressed, + child: const Text('Retry'), + ); + } + return TextButton( + key: buttonKey, + onPressed: onPressed, + child: const Text('Retry'), + ); +} diff --git a/app/lib/features/templates/ui/templates_frame.dart b/app/lib/features/templates/ui/templates_frame.dart new file mode 100644 index 00000000..5abd42e2 --- /dev/null +++ b/app/lib/features/templates/ui/templates_frame.dart @@ -0,0 +1,104 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; + +const templatesRefreshKey = ValueKey('templates-refresh'); +const templatesBackKey = ValueKey('templates-back'); + +/// The screen's native chrome. +/// +/// Standalone use keeps the host's own app bar with Back and Refresh. A shell +/// that already owns navigation passes [embedded], which drops the bar and +/// keeps Refresh at the top of the body. +class TemplatesFrame extends StatelessWidget { + const TemplatesFrame({ + super.key, + required this.body, + required this.embedded, + required this.canGoBack, + required this.refreshing, + required this.onBack, + required this.onRefresh, + }); + + final Widget body; + final bool embedded; + final bool canGoBack; + final bool refreshing; + final VoidCallback onBack; + final VoidCallback onRefresh; + + @override + Widget build(BuildContext context) { + if (embedded) return _embedded(context); + return usesCupertinoHost(context) + ? _cupertino(context) + : _material(context); + } + + Widget _embedded(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Align( + alignment: AlignmentDirectional.centerEnd, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: _refreshButton(context), + ), + ), + Expanded(child: body), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar( + leading: canGoBack + ? CupertinoButton( + key: templatesBackKey, + padding: EdgeInsets.zero, + onPressed: onBack, + child: const Icon(CupertinoIcons.back, semanticLabel: 'Back'), + ) + : null, + middle: const Text('Templates'), + trailing: _refreshButton(context), + ), + child: SafeArea(child: body), + ); + } + + Widget _material(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Templates'), + leading: canGoBack + ? BackButton(key: templatesBackKey, onPressed: onBack) + : null, + actions: [_refreshButton(context)], + ), + body: SafeArea(child: body), + ); + } + + Widget _refreshButton(BuildContext context) { + final onPressed = refreshing ? null : onRefresh; + if (usesCupertinoHost(context)) { + return CupertinoButton( + key: templatesRefreshKey, + padding: EdgeInsets.zero, + onPressed: onPressed, + child: const Icon(CupertinoIcons.refresh, semanticLabel: 'Refresh'), + ); + } + return IconButton( + key: templatesRefreshKey, + tooltip: 'Refresh', + onPressed: onPressed, + icon: const Icon(Icons.refresh), + ); + } +} diff --git a/app/notes/T1-gallery.md b/app/notes/T1-gallery.md new file mode 100644 index 00000000..eed7f4c0 --- /dev/null +++ b/app/notes/T1-gallery.md @@ -0,0 +1,175 @@ +# T1 — reusable native Templates gallery + +## Result + +`TemplatesScreen` is one reusable gallery over the server's actual template +catalogue. It lists every `list_templates` row, opens the selected template's +metadata and its source byte-for-byte in the host's selectable body, and offers +the browser's one create action. That action calls the already-landed +`showTemplateCreateDialog` unchanged, so validate-then-submit, Cancel, +create-only `submit` and the single accepted `detail` stay in the existing +prompt. The accepted detail is forwarded through the optional `onCreated` +callback. + +A refused refresh is reported above whichever body is current, including an open +template, with the host's native Retry; the selection and already-read rows are +kept. The screen's loading state, late-reply guard and single create path are +unchanged. + +Nothing is registered in the shell, Settings, routes or application; the +manager owns that next. No pipeline/gallery/create code was rewritten and no +run, schedule, publish, cancel or graph control exists here. + +## Files (all new; no tracked file modified) + +| File | Lines | Responsibility | +| --- | ---: | --- | +| `lib/features/templates/screen.dart` | 208 | Load/selection/create state, late-reply sequencing, failure banner above either body, embedded flag, system back | +| `lib/features/templates/ui/template_gallery.dart` | 138 | Catalog rows and honest loading/empty/full-failure states | +| `lib/features/templates/ui/template_detail.dart` | 168 | Browser wording, metadata, verbatim selectable source, create action, embedded Back row | +| `lib/features/templates/ui/templates_failure.dart` | 118 | Full failure state and the screen-level failed-refresh banner, each with native Retry | +| `lib/features/templates/ui/templates_frame.dart` | 104 | Native standalone app bar or embedded Refresh row; Back/Refresh controls | +| `test/features/templates/ui/template_gallery_test_support.dart` | 112 | Recording gateway, catalogue fixtures, Material/Cupertino host pump | +| `test/features/templates/ui/template_gallery_screen_test.dart` | 379 | States, retry, refresh, detail-refresh failure (both hosts, embedded), back, embedded, 2x, late/disposed replies | +| `test/features/templates/ui/template_gallery_create_test.dart` | 104 | Cancel sends nothing, verify+submit once, optional callback, Cupertino prompt | +| `tool/templates_gallery_probe.dart` | 178 | Isolated in-process fixture entry; default, empty and detail-refresh-refusal scenarios | +| `tool/templates_gallery_probe.mjs` | 386 | Loopback static server + real headless Chrome driver | +| `notes/T1-gallery.md` | — | This evidence | + +`TemplateEntry`, `TemplateRepository`, `TemplateRepositoryException`, +`ApiGateway`, `showTemplateCreateDialog` and its wording/keys are reused +unchanged. `pubspec.*`, `lib/main.dart`, `lib/application/`, `lib/shell/`, +Settings, routes, Pipelines, `web/`, the Go server and `android/` were not +touched. + +## Behaviour + +- Gallery wording is the browser's: `Loading templates…`, `No templates are + available on this server.`, a blank catalogue name as `(unnamed template)`, + description verbatim, and a blank detail heading falling back to the key. +- Detail shows the description (when non-blank), `Key`, `Includes a schedule` + (when true), `Definition source`, and the server's complete source in + `SelectableText`. The source is never trimmed, re-indented or re-encoded. +- The action is exactly `Create pipeline from this template`. It calls + `showTemplateCreateDialog` with the current repository, the selected entry and + the host's native flag. Opening the prompt, typing, or Cancel sends nothing. + Only the dialog's Create validates and then submits create-only; an accepted + detail reaches `onCreated` exactly once. +- Standalone Material uses `Scaffold`/`AppBar` with a native `BackButton` when a + template is open and a tooltip `Refresh` action; Cupertino uses + `CupertinoPageScaffold`/`CupertinoNavigationBar` with the native back chevron + and refresh icon. Doors are opened on the detail as this screen's own page, so + Android system back also returns to the gallery via `PopScope`. +- `embedded: true` drops the app bar, keeps a Refresh control at the body's + trailing top edge and shows a native Back row inside the detail, matching the + shell-owned-navigation contract used by other feature screens. +- Loading, empty and refusal have their own truthful states. A refusal shows the + server's own text and `Retry`; a refresh failure keeps already-loaded rows and + shows the refusal/`Retry` above them instead of blanking the gallery. The same + banner is rendered above an open template, so pressing Refresh on the detail + never fails silently; Retry re-reads with the template and rows kept. +- Only the newest `list_templates` generation may publish. A gateway change + clears the old server's rows and selection, an older reply is ignored, and a + reply completing after disposal is dropped (no `setState`). +- No stage-count read, stage list, Graph tab or mini graph is included: this + slice deliberately sends no per-card `validate`. The browser's stage count is + therefore not claimed here. The detail's metadata is description, key and + schedule flag; its source is complete. + +## Checks actually run + +``` +cd app +flutter analyze # No issues found +dart format --output=none --set-exit-if-changed \ + lib/features/templates test/features/templates/ui/template_gallery_*.dart \ + tool/templates_gallery_probe.dart # 0 changed +flutter test test/features/templates # 37 passed +flutter test # 690 passed +flutter build web -o /web-normal # ✓ Built +flutter build web --target=tool/templates_gallery_probe.dart \ + -o /probe-web # ✓ Built +``` + +The focused suite covers: loading then catalogue; empty; refusal + Retry; +failed refresh retaining rows; a failed refresh with the detail open on Material +and Cupertino, including the native Retry control and the template staying +open; the same failure in embedded mode; refresh re-reading without losing +selection; selection showing metadata/source with no validate/submit; +native/system back; embedded framing; Cupertino list/back/detail controls; 2x at +360×640 with no overflow; stale reply ignored after a gateway replacement; late +reply after disposal; Cancel sending nothing; exact `validate`/`submit` payloads; +callback once; optional callback; Cupertino prompt. + +## Browser evidence (real headless Chrome, loopback only) + +The probe's gateway is in-process; it never opens a socket and never contacts a +real Pipelines server. All runs are dark (`MaterialApp` standard dark theme / +`CupertinoThemeData(brightness: dark)`), with no font, colour or component-size +overrides. Each default run asserts: refusal + Retry; loading; actual rows; +selection metadata + `Definition source`; back; refresh adding +`Added after refresh`; Cancel with zero requests; accepted create with exactly +one validate and submit, exact +`{name: "Probe release", source: , create_only: true}`, +callback once, and Close sending nothing. + +- Material dark, 390×844, 1x — `public/t1-gallery/` + (`error`, `loading`, `gallery`, `detail`, `refreshed`, `create-blank`, `created`). +- Material dark, 360×640, 2x text — `public/t1-gallery-2x/` (same seven states). +- Cupertino dark, 390×844, 1x — `public/t1-gallery-cupertino-1x/` (same seven). +- Cupertino dark, 360×640, 2x text — `public/t1-gallery-cupertino/` (same seven). +- Material dark empty catalogue — `public/t1-gallery-empty/t1-gallery-empty-empty.png`. +- Material dark failed refresh with the detail open — + `public/t1-gallery-detail-refresh/` (`detail-refresh-error`, + `detail-refresh-retried`). +- Cupertino dark failed refresh with the detail open — + `public/t1-gallery-detail-refresh-cupertino/` (same two states). + +The new scenario loads the catalogue, opens `Release workflow`, presses Refresh +and the fixture read genuinely refuses. The run asserts the refusal and Retry +are present above the still-open definition source, that exactly two +`list_templates` reads and no `validate`/`submit` happened, then presses Retry, +asserts the banner clears, the template stays open and a third read happened. +Inspected both Material and Cupertino captures: the native banner sits above the +detail, then disappears after Retry without losing the template. + +Inspected screenshots: the Material dark gallery/detail, the 2x detail with +wrapped action and title, the Cupertino 1x gallery/detail, the 2x Cupertino +gallery (names now wrap to two lines rather than ellipsizing), the error/Retry +state and the created dialog with the exact success line. + +## Task diff + +``` +?? app/lib/features/templates/screen.dart +?? app/lib/features/templates/ui/template_detail.dart +?? app/lib/features/templates/ui/template_gallery.dart +?? app/lib/features/templates/ui/templates_failure.dart +?? app/lib/features/templates/ui/templates_frame.dart +?? app/test/features/templates/ui/template_gallery_create_test.dart +?? app/test/features/templates/ui/template_gallery_screen_test.dart +?? app/test/features/templates/ui/template_gallery_test_support.dart +?? app/tool/templates_gallery_probe.dart +?? app/tool/templates_gallery_probe.mjs +?? app/notes/T1-gallery.md +``` + +All are additions in the working tree. No tracked file changed, no concurrent +lane or manager commit was modified, and nothing was staged, committed, pushed +or deployed. `git diff --check` is clean. + +## Honest limits + +- Not wired into the shell/Settings/routes; this is reusable source, not a + normal-app preview entry. The manager owns registration. +- No real Pipelines server, credentials, operator pipeline or create request was + touched. Browser evidence uses the in-process fake gateway. +- Mobile (Android/iOS) is unverified: no Android/iOS build, emulator, device or + ADB. The Cupertino captures are Chrome's rendering of Cupertino widgets, not + iOS; VoiceOver/TalkBack was not run. +- Stage counts, stage lists and the Graph tab are intentionally not implemented + in this slice (no per-card validate), so they are not claimed as parity here. +- Browser captures remain standalone use only; `embedded: true` is covered by + widget tests, not by the headless-Chrome probe. +- `/artifacts`/live authenticated data and the real dark app-shell theme were + not exercised; the probe supplies the standard dark host themes. diff --git a/app/test/features/templates/ui/template_gallery_create_test.dart b/app/test/features/templates/ui/template_gallery_create_test.dart new file mode 100644 index 00000000..3308d4fb --- /dev/null +++ b/app/test/features/templates/ui/template_gallery_create_test.dart @@ -0,0 +1,104 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/screen.dart'; +import 'package:pipelines_app/features/templates/ui/template_create_wording.dart'; + +import '../data/template_test_support.dart' show source; +import 'template_gallery_test_support.dart'; + +Future openRelease(WidgetTester tester) async { + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(templateCreateActionKey)); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets( + 'Cancel sends nothing; Create validates and submits the verbatim source ' + 'once through the existing prompt', + (tester) async { + final gateway = GalleryGateway((type, fields) async { + if (type == 'list_templates') return templatesReply(galleryTemplates); + return acceptedCreate(type, fields); + }); + final created = []; + await pumpGallery(tester, gateway, onCreated: created.add); + await openRelease(tester); + + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text('Create from Release workflow'), findsOneWidget); + await tester.enterText(find.byKey(templateCreateNameKey), 'Café'); + await tester.pump(); + await tester.tap(find.byKey(templateCreateCancelKey)); + await tester.pumpAndSettle(); + + expect(find.byType(AlertDialog), findsNothing); + expect(gateway.callsOf('validate'), isEmpty); + expect(gateway.callsOf('submit'), isEmpty); + expect(created, isEmpty); + + await tester.tap(find.byKey(templateCreateActionKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templateCreateNameKey), findsOneWidget); + await tester.enterText(find.byKey(templateCreateNameKey), ' Café '); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.callsOf('validate').single.fields, {'source': source}); + expect(gateway.callsOf('submit').single.fields, { + 'name': 'Café', + 'source': source, + 'create_only': true, + }); + expect(gateway.callsOf('submit').single.fields.keys, [ + 'name', + 'source', + 'create_only', + ]); + expect(created, [ + {'id': 7, 'name': 'Created release'}, + ]); + expect( + find.text('Created "Created release". It is in the Pipelines list.'), + findsOneWidget, + ); + expect(find.text('Close'), findsOneWidget); + + await tester.tap(find.byKey(templateCreateCancelKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(created, hasLength(1)); + expect(gateway.callsOf('submit'), hasLength(1)); + }, + ); + + testWidgets('the callback is optional and Cupertino uses its native prompt', ( + tester, + ) async { + final gateway = GalleryGateway((type, fields) async { + if (type == 'list_templates') return templatesReply(galleryTemplates); + return acceptedCreate(type, fields); + }); + await pumpGallery(tester, gateway, cupertino: true); + await openRelease(tester); + + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + await tester.enterText(find.byKey(templateCreateNameKey), 'Cupertino'); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.callsOf('validate'), hasLength(1)); + expect(gateway.callsOf('submit'), hasLength(1)); + expect( + find.text('Created "Created release". It is in the Pipelines list.'), + findsOneWidget, + ); + expect(find.byKey(templateCreateCancelKey), findsOneWidget); + }); +} diff --git a/app/test/features/templates/ui/template_gallery_screen_test.dart b/app/test/features/templates/ui/template_gallery_screen_test.dart new file mode 100644 index 00000000..ca4d93dc --- /dev/null +++ b/app/test/features/templates/ui/template_gallery_screen_test.dart @@ -0,0 +1,379 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/screen.dart'; +import 'package:pipelines_app/features/templates/ui/template_detail.dart'; + +import '../data/template_test_support.dart' show source; +import 'template_gallery_test_support.dart'; + +void main() { + testWidgets('loading shows the exact line, then the server catalogue', ( + tester, + ) async { + final reply = Completer(); + final gateway = GalleryGateway((type, fields) => reply.future); + + await pumpGallery(tester, gateway, settle: false); + await tester.pump(); + + expect(find.byKey(templatesLoadingKey), findsOneWidget); + expect(find.text('Loading templates…'), findsOneWidget); + expect(gateway.calls.single.type, 'list_templates'); + expect(gateway.calls.single.fields, isEmpty); + + reply.complete(templatesReply(galleryTemplates)); + await tester.pumpAndSettle(); + + expect(find.byKey(templatesGalleryKey), findsOneWidget); + expect(find.text('Release workflow'), findsOneWidget); + expect(find.text('Ship a version'), findsOneWidget); + expect(find.text('(unnamed template)'), findsOneWidget); + expect(find.byKey(templatesLoadingKey), findsNothing); + }); + + testWidgets('an empty catalogue states it without inventing rows', ( + tester, + ) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(const []), + ); + + await pumpGallery(tester, gateway); + + expect(find.byKey(templatesEmptyKey), findsOneWidget); + expect( + find.text('No templates are available on this server.'), + findsOneWidget, + ); + expect(find.byKey(templatesGalleryKey), findsNothing); + }); + + testWidgets('a refusal offers Retry; a failed refresh keeps the rows', ( + tester, + ) async { + var mode = 'refuse'; + final gateway = GalleryGateway((type, fields) async { + if (type != 'list_templates') throw StateError('unexpected $type'); + if (mode == 'refuse') { + throw Exception('catalogue unavailable'); + } + return templatesReply(galleryTemplates); + }); + + await pumpGallery(tester, gateway); + + expect(find.byKey(templatesErrorKey), findsOneWidget); + expect(find.text('catalogue unavailable'), findsOneWidget); + expect(find.byKey(templatesGalleryKey), findsNothing); + + mode = 'ok'; + await tester.tap(find.byKey(templatesRetryKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templatesGalleryKey), findsOneWidget); + expect(find.text('Release workflow'), findsOneWidget); + + mode = 'refuse'; + await tester.tap(find.byKey(templatesRefreshKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templatesGalleryKey), findsOneWidget); + expect(find.text('Release workflow'), findsOneWidget); + expect(find.text('catalogue unavailable'), findsOneWidget); + expect(find.byKey(templatesErrorBannerKey), findsOneWidget); + expect(find.byKey(templatesErrorKey), findsNothing); + + mode = 'ok'; + await tester.tap(find.byKey(templatesBannerRetryKey)); + await tester.pumpAndSettle(); + expect(find.text('catalogue unavailable'), findsNothing); + expect(find.byKey(templatesErrorBannerKey), findsNothing); + expect(find.text('Release workflow'), findsOneWidget); + }); + + testWidgets('refresh re-reads the catalogue and keeps the selection', ( + tester, + ) async { + var calls = 0; + final gateway = GalleryGateway((type, fields) async { + calls++; + return templatesReply( + calls == 1 + ? galleryTemplates + : [ + ...galleryTemplates, + templateJson(key: 'new', name: 'New template'), + ], + ); + }); + + await pumpGallery(tester, gateway); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + expect(find.byKey(templateDetailKey), findsOneWidget); + + await tester.tap(find.byKey(templatesRefreshKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(find.text('Release workflow'), findsOneWidget); + expect(gateway.callsOf('list_templates'), hasLength(2)); + + await tester.tap(find.byKey(templatesBackKey)); + await tester.pumpAndSettle(); + expect(find.text('New template'), findsOneWidget); + }); + + testWidgets('selecting a template shows metadata and verbatim source only', ( + tester, + ) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + + await pumpGallery(tester, gateway); + expect(gateway.callsOf('list_templates'), hasLength(1)); + + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(find.text('Release workflow'), findsOneWidget); + expect(find.text('Ship a version'), findsOneWidget); + expect(find.text('Key'), findsOneWidget); + expect(find.text('Includes a schedule'), findsOneWidget); + expect(find.text(templateSourceLabel), findsOneWidget); + expect(selectableSource(source), findsOneWidget); + expect(selectableSource('release'), findsOneWidget); + expect(find.text(templateCreateActionLabel), findsOneWidget); + expect(gateway.callsOf('validate'), isEmpty); + expect(gateway.callsOf('submit'), isEmpty); + + await tester.tap(find.byKey(templatesBackKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templatesGalleryKey), findsOneWidget); + expect(find.byKey(templateDetailKey), findsNothing); + }); + + testWidgets('native back returns to the gallery', (tester) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + await pumpGallery(tester, gateway); + await tester.tap(find.byKey(templateRowKey('blank'))); + await tester.pumpAndSettle(); + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(selectableSource('blank'), findsOneWidget); + + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + + expect(find.byKey(templatesGalleryKey), findsOneWidget); + expect(find.byKey(templateDetailKey), findsNothing); + }); + + testWidgets('embedded use drops the app bar and keeps native detail back', ( + tester, + ) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + await pumpGallery(tester, gateway, embedded: true); + + expect(find.byType(AppBar), findsNothing); + expect(find.byKey(templatesRefreshKey), findsOneWidget); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + expect(find.byKey(templateDetailKey), findsOneWidget); + + await tester.tap(find.byKey(templateDetailBackKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templatesGalleryKey), findsOneWidget); + }); + + testWidgets('Cupertino host uses its own list, back and detail controls', ( + tester, + ) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + await pumpGallery(tester, gateway, cupertino: true); + + expect(find.byType(CupertinoListTile), findsNWidgets(2)); + expect(find.byType(Scaffold), findsNothing); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(selectableSource(source), findsOneWidget); + expect( + tester + .widget(find.byKey(templateCreateActionKey)) + .onPressed, + isNotNull, + ); + expect(find.byType(BackButton), findsNothing); + + await tester.tap(find.byKey(templatesBackKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoListTile), findsNWidgets(2)); + }); + + testWidgets( + 'a failed refresh with a template open is visible and retryable', + (tester) async { + for (final cupertino in [false, true]) { + var mode = 'ok'; + final gateway = GalleryGateway((type, fields) async { + if (type != 'list_templates') throw StateError('unexpected $type'); + if (mode == 'refuse') throw Exception('refresh unavailable'); + return templatesReply(galleryTemplates); + }); + + await pumpGallery(tester, gateway, cupertino: cupertino); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + expect(find.byKey(templateDetailKey), findsOneWidget); + + mode = 'refuse'; + await tester.tap(find.byKey(templatesRefreshKey)); + await tester.pumpAndSettle(); + + expect(gateway.callsOf('list_templates'), hasLength(2)); + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(find.byKey(templatesErrorBannerKey), findsOneWidget); + expect(find.text('refresh unavailable'), findsOneWidget); + expect(find.byKey(templatesBannerRetryKey), findsOneWidget); + expect(find.byKey(templatesErrorKey), findsNothing); + expect(find.text(templateSourceLabel), findsOneWidget); + expect(find.text(templateCreateActionLabel), findsOneWidget); + expect( + tester.widget(find.byKey(templatesBannerRetryKey)), + cupertino ? isA() : isA(), + ); + expect(tester.takeException(), isNull); + + mode = 'ok'; + await tester.tap(find.byKey(templatesBannerRetryKey)); + await tester.pumpAndSettle(); + + expect(find.text('refresh unavailable'), findsNothing); + expect(find.byKey(templatesErrorBannerKey), findsNothing); + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(find.text(templateSourceLabel), findsOneWidget); + expect(gateway.callsOf('list_templates'), hasLength(3)); + + await tester.tap(find.byKey(templatesBackKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templatesGalleryKey), findsOneWidget); + expect(find.text('Release workflow'), findsOneWidget); + expect(find.text('(unnamed template)'), findsOneWidget); + } + }, + ); + + testWidgets('an embedded failed refresh is visible above the open template', ( + tester, + ) async { + var mode = 'ok'; + final gateway = GalleryGateway((type, fields) async { + if (type != 'list_templates') throw StateError('unexpected $type'); + if (mode == 'refuse') throw Exception('refresh unavailable'); + return templatesReply(galleryTemplates); + }); + + await pumpGallery(tester, gateway, embedded: true); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + expect(find.byKey(templateDetailBackKey), findsOneWidget); + + mode = 'refuse'; + await tester.tap(find.byKey(templatesRefreshKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(templatesErrorBannerKey), findsOneWidget); + expect(find.text('refresh unavailable'), findsOneWidget); + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(find.byKey(templateDetailBackKey), findsOneWidget); + + mode = 'ok'; + await tester.tap(find.byKey(templatesBannerRetryKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(templatesErrorBannerKey), findsNothing); + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(gateway.callsOf('list_templates'), hasLength(3)); + }); + + testWidgets('2x text on a short phone has no overflow and stays reachable', ( + tester, + ) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + await pumpGallery( + tester, + gateway, + size: const Size(360, 640), + textScale: 2, + ); + + expect(tester.takeException(), isNull); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.text(templateCreateActionLabel), findsOneWidget); + expect(selectableSource(source), findsOneWidget); + expect(find.byKey(templatesBackKey), findsOneWidget); + }); + + testWidgets('only the newest reply wins and a disposed screen ignores one', ( + tester, + ) async { + final first = Completer(); + final stale = Completer(); + var calls = 0; + final gateway = GalleryGateway((type, fields) { + calls++; + if (calls == 1) return first.future; + if (calls == 2) return stale.future; + return Future.value( + templatesReply([templateJson(key: 'fresh', name: 'Fresh')]), + ); + }); + + await pumpGallery(tester, gateway, settle: false); + first.complete( + templatesReply([templateJson(key: 'old', name: 'Old reply')]), + ); + await tester.pumpAndSettle(); + expect(find.text('Old reply'), findsOneWidget); + + await tester.tap(find.byKey(templatesRefreshKey)); + await tester.pump(); + final replacement = GalleryGateway( + (type, fields) async => + templatesReply([templateJson(key: 'other', name: 'Other server')]), + ); + await pumpGallery(tester, replacement); + expect(find.text('Other server'), findsOneWidget); + + stale.complete( + templatesReply([templateJson(key: 'stale', name: 'Stale reply')]), + ); + await tester.pumpAndSettle(); + expect(find.text('Stale reply'), findsNothing); + expect(find.text('Other server'), findsOneWidget); + + final pending = Completer(); + final disposedGateway = GalleryGateway((type, fields) => pending.future); + await pumpGallery(tester, disposedGateway, settle: false); + await tester.pumpWidget(const SizedBox.shrink()); + pending.complete(templatesReply(galleryTemplates)); + await tester.pump(); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/features/templates/ui/template_gallery_test_support.dart b/app/test/features/templates/ui/template_gallery_test_support.dart new file mode 100644 index 00000000..9c94f9c4 --- /dev/null +++ b/app/test/features/templates/ui/template_gallery_test_support.dart @@ -0,0 +1,112 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/screen.dart'; + +import '../data/template_test_support.dart' show source; + +typedef GalleryHandler = + FutureOr Function(String type, JsonMap fields); + +/// A recording gateway whose replies come from [handler]. +class GalleryGateway implements ApiGateway { + GalleryGateway(this.handler); + + final GalleryHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); + + List<({String type, JsonMap fields})> callsOf(String type) => + calls.where((call) => call.type == type).toList(growable: false); +} + +JsonMap templateJson({ + required String key, + String name = '', + String description = '', + String? definition, + bool scheduled = false, +}) => { + 'key': key, + 'name': name, + 'description': description, + 'source': definition ?? source, + 'scheduled': scheduled, +}; + +JsonMap templatesReply(List templates) => {'templates': templates}; + +final galleryTemplates = [ + templateJson( + key: 'release', + name: 'Release workflow', + description: 'Ship a version', + scheduled: true, + ), + templateJson(key: 'blank', description: 'No display name'), +]; + +Future acceptedCreate(String type, JsonMap fields) async { + if (type == 'validate') return {'graph': {}}; + if (type == 'submit') { + return { + 'detail': {'id': 7, 'name': 'Created release'}, + }; + } + throw StateError('Unexpected request $type'); +} + +/// Pumps the gallery in a real Material or Cupertino host without fixed sizes. +Future pumpGallery( + WidgetTester tester, + GalleryGateway gateway, { + bool cupertino = false, + bool embedded = false, + ValueChanged? onCreated, + double textScale = 1, + Size size = const Size(800, 1000), + bool settle = true, +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + final screen = TemplatesScreen( + gateway: gateway, + embedded: embedded, + onCreated: onCreated, + ); + final home = embedded + ? (cupertino + ? CupertinoPageScaffold(child: screen) + : Scaffold(body: screen)) + : screen; + await tester.pumpWidget( + cupertino + ? CupertinoApp(builder: media, home: home) + : MaterialApp(builder: media, home: home), + ); + if (settle) await tester.pumpAndSettle(); +} + +Finder selectableSource(String text) => find.byWidgetPredicate( + (widget) => widget is SelectableText && widget.data == text, +); diff --git a/app/tool/templates_gallery_probe.dart b/app/tool/templates_gallery_probe.dart new file mode 100644 index 00000000..c42d26af --- /dev/null +++ b/app/tool/templates_gallery_probe.dart @@ -0,0 +1,178 @@ +import 'dart:async'; +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/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/templates/screen.dart'; + +/// Browser capture entrypoint for the reusable Templates gallery. +/// +/// The fixture gateway is in-process and records every request; nothing here +/// opens a socket or contacts a real server. Query parameters: +/// `host=material|cupertino`, `scale=` and +/// `scenario=default|empty|refresh-refusal`. The state published at +/// `globalThis.templatesGalleryProbe` is read by the driver. +const _source = ' name: "release"\n\tstages:\n - key: "añadir" 😀 \n'; + +const _galleryRows = [ + { + 'key': 'release', + 'name': 'Release workflow', + 'description': 'Ship a version', + 'source': _source, + 'scheduled': true, + }, + { + 'key': 'blank', + 'name': '', + 'description': 'No display name', + 'source': 'name: "unnamed"\n', + 'scheduled': false, + }, +]; + +class _ProbeGateway implements ApiGateway { + _ProbeGateway( + this.publish, { + required this.empty, + required this.failingRefresh, + }); + + final VoidCallback publish; + final bool empty; + final bool failingRefresh; + int listCalls = 0; + int validates = 0; + int submits = 0; + final List created = []; + String? lastSource; + JsonMap? lastSubmit; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type == 'list_templates') { + listCalls++; + publish(); + if (failingRefresh) { + // The catalogue loads, then a Refresh from the open template refuses so + // the driver can prove the failure is visible above that detail. + if (listCalls == 2) { + await Future.delayed(const Duration(milliseconds: 250)); + throw const ProtocolError('fixture refresh unavailable'); + } + return {'templates': _galleryRows}; + } + if (listCalls == 1 && !empty) { + // The first read refuses, so the driver can exercise the honest error + // state and Retry on a real host. + await Future.delayed(const Duration(milliseconds: 250)); + throw const ProtocolError('fixture catalogue unavailable'); + } + if (listCalls == 2) { + // Enough time to capture the loading state after Retry. + await Future.delayed(const Duration(milliseconds: 1200)); + } + if (empty) return {'templates': const []}; + return { + 'templates': [ + ..._galleryRows, + if (listCalls >= 3) + { + 'key': 'added', + 'name': 'Added after refresh', + 'description': 'Proves the catalogue was re-read', + 'source': 'name: "added"\n', + 'scheduled': false, + }, + ], + }; + } + if (type == 'validate') { + validates++; + lastSource = fields['source'] as String?; + publish(); + await Future.delayed(const Duration(milliseconds: 200)); + return { + 'graph': {'stages': const []}, + }; + } + if (type == 'submit') { + submits++; + lastSubmit = Map.from(fields); + publish(); + return { + 'detail': {'id': 41, 'name': 'Probe created'}, + }; + } + throw StateError('The templates probe does not implement $type'); + } +} + +void main() => runApp(const _ProbeApp()); + +class _ProbeApp extends StatefulWidget { + const _ProbeApp(); + + @override + State<_ProbeApp> createState() => _ProbeAppState(); +} + +class _ProbeAppState extends State<_ProbeApp> { + late final _params = Uri.base.queryParameters; + late final _cupertino = _params['host'] == 'cupertino'; + late final _scale = double.tryParse(_params['scale'] ?? '') ?? 1; + late final _gateway = _ProbeGateway( + _publish, + empty: _params['scenario'] == 'empty', + failingRefresh: _params['scenario'] == 'refresh-refusal', + ); + + void _publish() { + globalContext.setProperty( + 'templatesGalleryProbe'.toJS, + { + 'listCalls': _gateway.listCalls, + 'validates': _gateway.validates, + 'submits': _gateway.submits, + 'created': _gateway.created, + 'lastSource': _gateway.lastSource, + 'lastSubmit': _gateway.lastSubmit, + }.jsify(), + ); + } + + void _created(JsonMap detail) { + _gateway.created.add(detail); + _publish(); + } + + @override + Widget build(BuildContext context) { + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(_scale)), + child: app!, + ); + final screen = TemplatesScreen(gateway: _gateway, onCreated: _created); + if (_cupertino) { + return CupertinoApp( + theme: CupertinoThemeData(brightness: Brightness.dark), + builder: scaled, + home: screen, + ); + } + return MaterialApp( + theme: ThemeData(brightness: Brightness.dark), + builder: scaled, + home: screen, + ); + } +} diff --git a/app/tool/templates_gallery_probe.mjs b/app/tool/templates_gallery_probe.mjs new file mode 100644 index 00000000..6ad5bac1 --- /dev/null +++ b/app/tool/templates_gallery_probe.mjs @@ -0,0 +1,386 @@ +import { createServer } from 'node:http'; +import { readFile, mkdir, mkdtemp, 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'; + +// Real-browser acceptance for the reusable Templates gallery. +// +// Usage (from app/): +// flutter build web --target=tool/templates_gallery_probe.dart \ +// -o build/templates_gallery_probe_web +// OPENCODE_ARTIFACT_DIR= node tool/templates_gallery_probe.mjs +// +// PROBE_HOST (material|cupertino), PROBE_SCALE, PROBE_WIDTH/PROBE_HEIGHT, +// PROBE_SCENARIO (default|empty|refresh-refusal) and PROBE_CAPTURE_PREFIX +// select the host and evidence. The fixture gateway is in-process: no socket +// is opened and no real Pipelines server is contacted. + +const root = resolve(process.env.PROBE_WEB_ROOT ?? 'build/templates_gallery_probe_web'); +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR; +if (!artifactDir) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(artifactDir, { recursive: true }); +const width = Number(process.env.PROBE_WIDTH ?? 390); +const height = Number(process.env.PROBE_HEIGHT ?? 844); +const textScale = process.env.PROBE_SCALE ?? '1'; +const host = process.env.PROBE_HOST ?? 'material'; +const scenario = process.env.PROBE_SCENARIO ?? 'default'; +const capturePrefix = process.env.PROBE_CAPTURE_PREFIX ?? 't1-gallery'; +const deviceScaleFactor = Number(process.env.PROBE_DPR ?? 1); + +const MIME = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.otf': 'font/otf', + '.ttf': 'font/ttf', +}; +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)) { + res.writeHead(403).end(); + return; + } + 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' }).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(), 'templates-gallery-chrome-')); +const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [ + '--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; +}); + +async function waitFor(check, label, attempts = 160) { + for (let attempt = 0; attempt < attempts; attempt++) { + const value = await check(); + 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(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.method === 'Runtime.exceptionThrown') { + console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails?.exception?.description)); + } + 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 target = (await send('Target.createTarget', { url: 'about:blank' })).result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor, mobile: true }, + session, + ); + await send( + 'Emulation.setEmulatedMedia', + { features: [{ name: 'prefers-color-scheme', value: 'dark' }] }, + session, + ); + + 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(`Page exception: ${JSON.stringify(response.result.exceptionDetails)}`); + } + return response.result?.result?.value; + }; + + const semanticText = () => + 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')); + if (el.value) chunks.push(String(el.value)); + } + if (document.body?.innerText) chunks.push(document.body.innerText); + return [...new Set(chunks)].join('\\n'); + })()`); + + const labels = () => + evaluate( + "[...document.querySelectorAll('flt-semantics')].map((el) => (el.getAttribute('aria-label') || el.innerText || '').trim()).filter(Boolean)", + ); + + const assertBody = async (text) => { + try { + await waitFor( + async () => (await semanticText()).includes(text), + `body to contain ${JSON.stringify(text)}`, + ); + } catch (error) { + throw new Error(`${error.message}\nBody now:\n${(await semanticText()).slice(0, 3000)}`); + } + }; + + const clickLabel = async (label, { contains = false } = {}) => { + const point = await evaluate(`(() => { + const needle = ${JSON.stringify(label)}; + const candidates = [...document.querySelectorAll('flt-semantics')].filter((el) => { + const text = (el.getAttribute('aria-label') || el.innerText || '').trim(); + return ${contains ? 'text.includes(needle)' : 'text === needle'}; + }); + const target = candidates.find((el) => + ['button', 'tab', 'link', 'checkbox', 'menuitem'].includes(el.getAttribute('role')), + ) ?? candidates[0]; + if (!target) return null; + const r = target.getBoundingClientRect(); + if (r.width === 0 || r.height === 0) return null; + return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; + })()`); + if (!point) { + throw new Error(`Could not click ${JSON.stringify(label)}. Labels: ${JSON.stringify(await labels())}`); + } + await send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session); + await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session); + await delay(400); + }; + + const typeName = async (value) => { + const focused = await evaluate(`(() => { + const input = document.querySelector('input'); + if (!input) return false; + input.focus(); + input.select?.(); + input.setSelectionRange?.(0, (input.value || '').length); + return true; + })()`); + if (!focused) throw new Error('The name field was not exposed as a semantics input'); + await delay(300); + await send('Input.insertText', { text: value }, session); + await delay(400); + }; + + const state = () => evaluate('globalThis.templatesGalleryProbe ?? null'); + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data; + const path = join(artifactDir, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + return path; + }; + + const checks = []; + const captures = []; + await send( + 'Page.navigate', + { url: `${origin}/?scale=${textScale}&host=${host}&scenario=${scenario}` }, + session, + ); + await waitFor( + () => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), + 'semantics placeholder', + ); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + + if (scenario === 'empty') { + await assertBody('No templates are available on this server.'); + const emptyState = await state(); + if (emptyState?.listCalls !== 1) { + throw new Error(`The empty catalogue made unexpected requests: ${JSON.stringify(emptyState)}`); + } + captures.push(await capture(`${capturePrefix}-empty`)); + checks.push({ check: 'empty catalogue stated honestly', state: emptyState }); + } else if (scenario === 'refresh-refusal') { + // The catalogue loads, a template is open, and Refresh genuinely refuses: + // the refusal must stay visible above that detail, with Retry. + await assertBody('Release workflow'); + await clickLabel('Release workflow', { contains: true }); + await assertBody('Definition source'); + const before = await state(); + if (before?.listCalls !== 1 || before?.validates !== 0 || before?.submits !== 0) { + throw new Error(`Opening the template made unexpected requests: ${JSON.stringify(before)}`); + } + + await clickLabel('Refresh'); + await assertBody('fixture refresh unavailable'); + await assertBody('Retry'); + await assertBody('Definition source'); + await assertBody('Create pipeline from this template'); + const refused = await state(); + if (refused?.listCalls !== 2 || refused?.validates !== 0 || refused?.submits !== 0) { + throw new Error(`The failed refresh did not stay read-only: ${JSON.stringify(refused)}`); + } + captures.push(await capture(`${capturePrefix}-detail-refresh-error`)); + checks.push({ check: 'failed refresh visible above the open template', state: refused }); + + await clickLabel('Retry'); + await waitFor( + async () => !(await semanticText()).includes('fixture refresh unavailable'), + 'the refusal banner to clear after Retry', + ); + await assertBody('Definition source'); + const retried = await state(); + if (retried?.listCalls !== 3) { + throw new Error(`Retry did not re-read exactly once: ${JSON.stringify(retried)}`); + } + captures.push(await capture(`${capturePrefix}-detail-refresh-retried`)); + checks.push({ check: 'Retry re-read while keeping the template open', state: retried }); + } else { + // The first read genuinely refuses; the screen must say so and retry. + await assertBody('fixture catalogue unavailable'); + await assertBody('Retry'); + const failed = await state(); + if (failed?.listCalls !== 1) { + throw new Error(`The refusal state made unexpected requests: ${JSON.stringify(failed)}`); + } + captures.push(await capture(`${capturePrefix}-error`)); + checks.push({ check: 'catalogue refusal shown with Retry', state: failed }); + + await clickLabel('Retry'); + await assertBody('Loading templates…'); + captures.push(await capture(`${capturePrefix}-loading`)); + await assertBody('Release workflow'); + await assertBody('(unnamed template)'); + await assertBody('Ship a version'); + const gallery = await state(); + if (gallery?.listCalls !== 2) { + throw new Error(`Retry did not re-read exactly once: ${JSON.stringify(gallery)}`); + } + captures.push(await capture(`${capturePrefix}-gallery`)); + checks.push({ check: 'retry loaded the actual catalogue rows', state: gallery }); + + await clickLabel('Release workflow', { contains: true }); + await assertBody('Definition source'); + await assertBody('Key'); + await assertBody('Includes a schedule'); + await assertBody('Create pipeline from this template'); + const detail = await state(); + if (detail?.validates !== 0 || detail?.submits !== 0) { + throw new Error(`Opening a template sent a write: ${JSON.stringify(detail)}`); + } + captures.push(await capture(`${capturePrefix}-detail`)); + checks.push({ check: 'selected template shows metadata and verbatim source', state: detail }); + + await clickLabel('Back'); + await assertBody('Release workflow'); + await clickLabel('Refresh'); + await assertBody('Added after refresh'); + const refreshed = await state(); + if (refreshed?.listCalls !== 3) { + throw new Error(`Refresh made unexpected requests: ${JSON.stringify(refreshed)}`); + } + captures.push(await capture(`${capturePrefix}-refreshed`)); + checks.push({ check: 'native back returned and refresh re-read the catalogue', state: refreshed }); + + await clickLabel('Release workflow', { contains: true }); + await assertBody('Create pipeline from this template'); + await clickLabel('Create pipeline from this template'); + await assertBody('Create from Release workflow'); + await assertBody('New pipeline name (required)'); + captures.push(await capture(`${capturePrefix}-create-blank`)); + await typeName('Probe release'); + await clickLabel('Cancel'); + await waitFor(async () => !(await semanticText()).includes('Create from Release workflow'), 'the prompt to close'); + const cancelled = await state(); + if (cancelled?.validates !== 0 || cancelled?.submits !== 0 || cancelled?.created?.length !== 0) { + throw new Error(`Cancel sent a request: ${JSON.stringify(cancelled)}`); + } + checks.push({ check: 'Cancel sent nothing', state: cancelled }); + + await waitFor( + async () => (await semanticText()).includes('Create pipeline from this template'), + 'the detail after the prompt closed', + ); + await clickLabel('Create pipeline from this template'); + await assertBody('Create from Release workflow'); + await typeName('Probe release'); + await clickLabel('Create'); + await assertBody('Created "Probe created". It is in the Pipelines list.'); + const created = await state(); + if (created?.validates !== 1 || created?.submits !== 1 || created?.created?.length !== 1) { + throw new Error(`The accepted create was not reported exactly once: ${JSON.stringify(created)}`); + } + if (created.lastSubmit?.name !== 'Probe release' || created.lastSubmit?.create_only !== true) { + throw new Error(`Submit payload drifted: ${JSON.stringify(created.lastSubmit)}`); + } + const verbatim = ' name: "release"\n\tstages:\n - key: "añadir" 😀 \n'; + if (created.lastSubmit?.source !== created.lastSource || created.lastSource !== verbatim) { + throw new Error(`Source was not sent verbatim: ${JSON.stringify(created)}`); + } + captures.push(await capture(`${capturePrefix}-created`)); + checks.push({ + check: 'accepted create forwarded the detail once with the verbatim source', + state: created, + }); + + await clickLabel('Close'); + await waitFor(async () => !(await semanticText()).includes('Create from Release workflow'), 'the prompt to close'); + const closed = await state(); + if (closed?.created?.length !== 1 || closed?.submits !== 1) { + throw new Error(`Close changed the request counts: ${JSON.stringify(closed)}`); + } + checks.push({ check: 'Close dismissed without another request', state: closed }); + } + + console.log(JSON.stringify({ + ok: true, + origin, + viewport: { width, height }, + deviceScaleFactor, + textScale, + host, + scenario, + checks, + captures, + }, 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 }); +} From ff9d3ce4a8480f41db610b7bfe3fad0dd3c93bc2 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:06:39 +0100 Subject: [PATCH 07/17] fix(app): use native schedule text roles instead of fixed sizes and weights --- .../ui/editor/schedule_editor_fields.dart | 4 ++-- .../schedules/ui/list/schedule_list_row.dart | 20 +++++++------------ .../ui/list/schedule_list_toolbar.dart | 3 +-- 3 files changed, 10 insertions(+), 17 deletions(-) diff --git a/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart b/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart index 044a98e3..f33476b7 100644 --- a/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart +++ b/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart @@ -6,8 +6,8 @@ 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, + // The host's own secondary-label style; no invented point size. + return CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith( color: CupertinoColors.secondaryLabel.resolveFrom(context), ); } diff --git a/app/lib/features/schedules/ui/list/schedule_list_row.dart b/app/lib/features/schedules/ui/list/schedule_list_row.dart index 010bf53b..110fb2f9 100644 --- a/app/lib/features/schedules/ui/list/schedule_list_row.dart +++ b/app/lib/features/schedules/ui/list/schedule_list_row.dart @@ -80,28 +80,22 @@ class ScheduleListRow extends StatelessWidget { Text(value, style: _metaStyle(context)); TextStyle? _titleStyle(BuildContext context) => cupertino - ? CupertinoTheme.of( - context, - ).textTheme.textStyle.copyWith(fontWeight: FontWeight.w600) - : Theme.of( - context, - ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600); + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleMedium; TextStyle? _bodyStyle(BuildContext context) => cupertino ? CupertinoTheme.of(context).textTheme.textStyle : null; TextStyle? _metaStyle(BuildContext context) => cupertino - ? CupertinoTheme.of(context).textTheme.textStyle.copyWith( - fontSize: 14, - color: _secondaryColor(context), - ) + ? CupertinoTheme.of( + context, + ).textTheme.tabLabelTextStyle.copyWith(color: _secondaryColor(context)) : Theme.of( context, ).textTheme.bodySmall?.copyWith(color: _secondaryColor(context)); - TextStyle? _statusStyle(BuildContext context) => _metaStyle( - context, - )?.copyWith(color: _statusColor(context), fontWeight: FontWeight.w600); + TextStyle? _statusStyle(BuildContext context) => + _metaStyle(context)?.copyWith(color: _statusColor(context)); Color _secondaryColor(BuildContext context) => cupertino ? CupertinoColors.secondaryLabel.resolveFrom(context) diff --git a/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart b/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart index 374c7424..4e01c4fb 100644 --- a/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart +++ b/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart @@ -169,8 +169,7 @@ class ScheduleListToolbar extends StatelessWidget { } TextStyle? _metaStyle(BuildContext context) => cupertino - ? CupertinoTheme.of(context).textTheme.textStyle.copyWith( - fontSize: 14, + ? CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith( color: CupertinoColors.secondaryLabel.resolveFrom(context), ) : Theme.of(context).textTheme.bodySmall?.copyWith( From 7219c5a3e300c7cbc702b45dad3c7313ace430da Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:07:45 +0100 Subject: [PATCH 08/17] docs(app): record template gallery acceptance and landing --- app/WORK.md | 2 +- app/notes/T1-gallery.md | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index ef928a2d..8730b539 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -45,7 +45,7 @@ All work under app/. Existing applications remain running and unchanged. | C3-state | Chat draft/send/stop controller | run75 /565cdaa |10min MET target; manager reviewed per-chat persistence, stable intent id, refusal restore, queued flag | merged main; ancestry verified | composer UI next | | C3-form | Native composer control | run? pending | drafts/send/stop UI atop75 | queued | pending | | Chat screen | Live Chat destination + read-only history | run79 /flutter/chat-live-screen | list/detail routing, paging, live one-thread, reconnect | running | pending | -| Templates gallery | Native template gallery/detail | run76 /flutter/templates-gallery | actual catalogue/source + create prompt forwarding | running | pending | +| Templates gallery | run76 /c56b5d45 | manager re-ran38 templates tests, rebuilt fixture;7 probe checks/7 captures incl inspected detail | merged main; ancestry verified | entry/route registration pending | | Stage definition | Native authored stage pane | run77 /flutter/stage-definition | pinned definition identity, outcomes/tools/raw unknown | running | pending | | Schedule form | Native schedule draft editor | run78 /flutter/schedule-form | binds74, no save engine | running | pending | diff --git a/app/notes/T1-gallery.md b/app/notes/T1-gallery.md index eed7f4c0..42d08564 100644 --- a/app/notes/T1-gallery.md +++ b/app/notes/T1-gallery.md @@ -1,5 +1,13 @@ # T1 — reusable native Templates gallery +Manager acceptance: re-ran the templates suite (38 tests) and rebuilt the +in-process fixture. Seven probe checks pass with seven captures under approved +temp/templates-gallery-browser; the selected-template capture was inspected and +shows metadata, the verbatim selectable source and the native create action with +one bar. No real template was created or submitted; every request came from the +fixture gateway. Settings/route registration and a post-create pipelines-list +refresh are still manager wiring, not claimed here. + ## Result `TemplatesScreen` is one reusable gallery over the server's actual template From 08e216a2fa105a8f9a26309d13eb87578bb1c168 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:12:21 +0100 Subject: [PATCH 09/17] test(app): verify recorded Changes navigation in the real app flow --- app/tool/runs_probe.mjs | 59 ++++++++++++++++++++++++---------- app/tool/runs_probe_server.mjs | 20 ++++++++++++ 2 files changed, 62 insertions(+), 17 deletions(-) diff --git a/app/tool/runs_probe.mjs b/app/tool/runs_probe.mjs index 846cc110..4c2f5fcf 100644 --- a/app/tool/runs_probe.mjs +++ b/app/tool/runs_probe.mjs @@ -260,35 +260,57 @@ try { await assertBody('Original prompt'); await assertBody('Timeline'); await assertBody('build · visit 3'); - captures.push(await capture('i1-runs-phone-detail')); - await assertOcr(captures[5], 'fixture prompt with spaces'); + const detailCapture = await capture('i1-runs-phone-detail'); + captures.push(detailCapture); + await assertOcr(detailCapture, 'fixture prompt with spaces'); + + // The recorded Changes action opens the landed viewer for this run's steps: + // the recorded file, its rendered diff, and back to the same detail. + await clickText('Changes'); + await assertBody('1 file changed'); + await assertBody('lib/features/fixture.dart'); + captures.push(await capture('changes-phone-list')); + await clickText('lib/features/fixture.dart', { contains: true }); + await assertBody('Rendered'); + await assertBody('added fixture line'); + await assertBody('removed fixture line'); + captures.push(await capture('changes-phone-diff')); + await clickText('Close diff'); + await assertBody('lib/features/fixture.dart'); + await delay(600); + await clickText('Back', { contains: true }); + await assertBody('Original prompt'); await setSize(1280, 800); await assertBody('Original prompt'); - captures.push(await capture('i1-runs-desktop-detail')); - await assertOcr(captures[6], 'fixture prompt with spaces'); + const desktopDetail = await capture('i1-runs-desktop-detail'); + captures.push(desktopDetail); + await assertOcr(desktopDetail, 'fixture prompt with spaces'); await setSize(390, 844); await clickText('Input'); await wheel(250); await delay(300); - captures.push(await capture('i1-runs-phone-detail-input')); - await assertOcr(captures[7], 'input payload'); + const inputCapture = await capture('i1-runs-phone-detail-input'); + captures.push(inputCapture); + await assertOcr(inputCapture, 'input payload'); await scrollUntil('Output'); await clickText('Output'); await wheel(250); await delay(300); - captures.push(await capture('i1-runs-phone-detail-output')); - await assertOcr(captures[8], 'answer'); + const outputCapture = await capture('i1-runs-phone-detail-output'); + captures.push(outputCapture); + await assertOcr(outputCapture, 'answer'); await scrollUntil('Metrics'); await clickText('Metrics'); await wheel(300); await delay(300); - captures.push(await capture('i1-runs-phone-detail-metrics')); - await assertOcr(captures[9], 'Total tokens'); - await assertOcr(captures[9], 'Reported cost'); + const metricsCapture = await capture('i1-runs-phone-detail-metrics'); + captures.push(metricsCapture); + await assertOcr(metricsCapture, 'Total tokens'); + await assertOcr(metricsCapture, 'Reported cost'); // Browser Back/Forward move between the in-app routes, not out of the app. const path = () => evaluate('location.pathname'); @@ -305,8 +327,9 @@ try { async () => (await semanticText()).includes('Fixture live run'), 'browser Back to the runs list', ); - captures.push(await capture('i1-runs-phone-browser-back-list')); - await assertOcr(captures[10], 'Fixture live run'); + const backListCapture = await capture('i1-runs-phone-browser-back-list'); + captures.push(backListCapture); + await assertOcr(backListCapture, 'Fixture live run'); await evaluate('history.forward()'); await waitFor( @@ -333,8 +356,9 @@ try { if (duringDrop.includes(raw)) throw new Error(`Raw transport text shown: ${raw}`); } if ((await path()) !== '/runs/1') throw new Error(`Drop moved the URL to ${await path()}`); - captures.push(await capture('i1-reconnect-detail-retained-phone')); - await assertOcr(captures[13], 'Original prompt'); + const retainedCapture = await capture('i1-reconnect-detail-retained-phone'); + captures.push(retainedCapture); + await assertOcr(retainedCapture, 'Original prompt'); // Accepting again plus Retry restores the same detail without a remount. const accepted = await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' }); @@ -359,12 +383,13 @@ try { for (const raw of ['WebSocketException', 'WebSocketChannelException', 'Failed to connect']) { if (gate.includes(raw)) throw new Error(`Gate printed raw transport text: ${raw}`); } - captures.push(await capture('i1-gate-unavailable-friendly-phone')); + const gateCapture = await capture('i1-gate-unavailable-friendly-phone'); + captures.push(gateCapture); await delay(1500); if (!(await semanticText()).includes('Pipelines server unavailable')) { throw new Error('Gate left the unavailable state while retrying'); } - await assertOcr(captures[15], 'Pipelines server unavailable'); + await assertOcr(gateCapture, 'Pipelines server unavailable'); await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' }); await clickText('Retry'); diff --git a/app/tool/runs_probe_server.mjs b/app/tool/runs_probe_server.mjs index b9ece509..2ae957f1 100644 --- a/app/tool/runs_probe_server.mjs +++ b/app/tool/runs_probe_server.mjs @@ -110,6 +110,26 @@ function detail(id, live, canceled = false) { status: 'completed', outcome: 'success', target: '#success', + file_changes: { + status: 'complete', + scope: 'Git tracked and nonignored files in the run directory', + files: [ + { + path: 'lib/features/fixture.dart', + kind: 'modified', + patch: + '--- a/lib/features/fixture.dart\n' + + '+++ b/lib/features/fixture.dart\n' + + '@@ -1,2 +1,2 @@\n' + + ' context line\n' + + '-removed fixture line\n' + + '+added fixture line\n', + }, + ], + skipped: 0, + omitted: 0, + diagnostic: '', + }, }, { stage: 'test', From 38f8576c84c0af21ffb102d1ad32697c221db0dc Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:14:04 +0100 Subject: [PATCH 10/17] feat(app): add the pure native attention model Port the browser's Needs-you list, dismissal bookkeeping and attention transition ledger as widget-free Dart under lib/features/attention/domain/. Includes the local-day window, export-wait exclusion, {runId}:{kind} identities, sorted dismissal storage and focused regressions. --- .../attention/domain/attention_models.dart | 245 +++++++++++++ .../domain/attention_transitions.dart | 136 +++++++ app/notes/R4-attention.md | 61 ++++ .../attention/attention_dismissals_test.dart | 113 ++++++ .../attention/attention_models_test.dart | 334 ++++++++++++++++++ .../attention/attention_transitions_test.dart | 224 ++++++++++++ 6 files changed, 1113 insertions(+) create mode 100644 app/lib/features/attention/domain/attention_models.dart create mode 100644 app/lib/features/attention/domain/attention_transitions.dart create mode 100644 app/notes/R4-attention.md create mode 100644 app/test/features/attention/attention_dismissals_test.dart create mode 100644 app/test/features/attention/attention_models_test.dart create mode 100644 app/test/features/attention/attention_transitions_test.dart diff --git a/app/lib/features/attention/domain/attention_models.dart b/app/lib/features/attention/domain/attention_models.dart new file mode 100644 index 00000000..0f89d2cc --- /dev/null +++ b/app/lib/features/attention/domain/attention_models.dart @@ -0,0 +1,245 @@ +import 'dart:convert'; + +import '../../../core/api_gateway.dart'; + +/// The two things the attention surface ranks, most important first. The rank +/// orders the list; the wire name is what a dismissal identity is keyed by. +/// +/// This mirrors the browser's pure `web/src/attention.js` model: only a run +/// parked on a person ([AttentionKind.decision]) and a failed run +/// ([AttentionKind.failed]) need the operator. A waiting run that is really an +/// audit/export handoff asks nobody, so it is excluded by [attentionKindForRun]. +enum AttentionKind { + decision(0, 'Decision'), + failed(1, 'Failed'); + + const AttentionKind(this.rank, this.wireName); + + final int rank; + + /// The spelling used in a persisted `{runId}:{kind}` identity. + final String wireName; +} + +/// The local storage key shared with the browser client: one JSON array of +/// `{runId}:{kind}` strings. A stored dismissal itself never expires; the +/// surface's local-day window is applied when entries are read, not here. +const attentionStorageKey = 'pipelines.web.attention.v1'; + +/// The run id a summary or pushed frame carries, or null when it is malformed. +/// The server ids are positive integers; anything else cannot identify an entry. +int? attentionRunId(dynamic value) { + final id = value is num + ? (value.isFinite ? value.toInt() : null) + : int.tryParse('${value ?? ''}'.trim()); + return id != null && id > 0 ? id : null; +} + +/// The attention kind a server status word maps to. Only the server's own +/// `waiting` and `failed` words qualify; queued, running, succeeded, canceled, +/// interrupted and unknown words ask nobody. A waiting run's *reason* is +/// checked by [attentionKindForRun], because the status word alone cannot tell a +/// human decision from an export handoff. +AttentionKind? attentionKindOf(dynamic status) { + switch (_word(status)) { + case 'waiting': + return AttentionKind.decision; + case 'failed': + return AttentionKind.failed; + default: + return null; + } +} + +/// The attention kind a complete run summary maps to, or null when it asks +/// nobody. +/// +/// A `waiting` run is listed only when it is actually waiting on a person. It is +/// not a Decision when the server recorded a session audit/export handoff +/// (`export_pending_sequence > 0`), so a machine export wait never reaches the +/// operator's "Needs you" list. +/// +/// `resource_wait` is deliberately not consulted, matching `web/src/attention.js` +/// and the Android client: it was retired server-side, and a stale value carried +/// onto a waiting run must not hide a genuine human decision. +AttentionKind? attentionKindForRun(JsonMap run) { + final kind = attentionKindOf(run['status']); + if (kind != AttentionKind.decision) return kind; + if (_positive(run['export_pending_sequence'])) return null; + return kind; +} + +/// The identity of one run+kind entry; the unit an explicit dismissal removes. +String attentionKey(int runId, AttentionKind kind) => '$runId:${kind.wireName}'; + +/// What one entry asks of the operator, in the operator's words. A failed run +/// shows the server's own diagnostic when it recorded one. +String attentionDetail(AttentionKind kind, JsonMap run) { + if (kind == AttentionKind.decision) return 'Waiting for your decision'; + final diagnostic = '${run['diagnostic'] ?? ''}'.trim(); + return diagnostic.isNotEmpty ? diagnostic : 'Run failed'; +} + +/// The one-line secondary text for a row: `{pipeline} · {detail}`. +String attentionRowDescription(AttentionEntry entry) => + '${entry.pipeline} · ${entry.detail}'; + +/// The bell action's accessible name: the bare `Notifications` when nothing +/// needs the operator, else the count. +String attentionBadgeLabel(int count) => + count > 0 ? 'Notifications, $count needing attention' : 'Notifications'; + +/// One run that needs the operator. +/// +/// The original summary map is kept whole, so fields this model does not read — +/// or fields a newer server adds — remain available to the caller unchanged. +/// Only [attentionEntryFor] constructs an entry, so [runId] is always a validated +/// positive server id rather than a getter that could throw. +class AttentionEntry { + const AttentionEntry._({ + required this.run, + required this.kind, + required this.runId, + }); + + final JsonMap run; + final AttentionKind kind; + final int runId; + + String get pipeline => '${run['name'] ?? ''}'; + String get detail => attentionDetail(kind, run); + String get key => attentionKey(runId, kind); + + /// The trimmed title else the pipeline label. + String get label { + final title = '${run['title'] ?? ''}'.trim(); + return title.isNotEmpty ? title : pipeline; + } + + /// The run's own recency, used only for ordering equal kinds newest-first. + /// A finished run is ordered by `finished_at`; a still-waiting one by its + /// creation time. + String get recency { + final finished = '${run['finished_at'] ?? ''}'; + return finished.trim().isNotEmpty ? finished : '${run['created_at'] ?? ''}'; + } +} + +/// The entry for one qualifying run, or null when it asks nobody. +AttentionEntry? attentionEntryFor(JsonMap run) { + final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']); + final kind = attentionKindForRun(run); + if (runId == null || kind == null) return null; + return AttentionEntry._(run: run, kind: kind, runId: runId); +} + +/// The start of the operator's local day. "Needs you" is a to-do list for what +/// changed now, so callers pass this as [attentionEntries]' `since`; yesterday's +/// failures are history, not a badge that follows every device for ever. Inject +/// [now] for a deterministic test; production callers pass nothing. +DateTime startOfLocalDay({DateTime? now}) { + final local = (now ?? DateTime.now()).toLocal(); + return DateTime(local.year, local.month, local.day); +} + +/// The ordered attention list: one entry per qualifying run, minus any identity +/// the operator explicitly dismissed and minus work older than [since]. +/// +/// Order matches the browser: kind rank (Decision before Failed), then recency +/// descending (the server's timestamp text, `finished_at` else `created_at`), +/// then run id descending so equal rows never reshuffle between reads. +/// +/// [since] is the local-day cutoff ([startOfLocalDay]) the bell, the sheet and +/// Clear all pass. As in `web/src/attention.js`, the cutoff applies only when the +/// entry's recency parses as a timestamp; a blank or unreadable recency is kept. +/// A null or epoch-zero cutoff shows everything. +List attentionEntries( + Iterable? runs, { + Set dismissed = const {}, + DateTime? since, +}) { + final entries = []; + for (final run in runs ?? const []) { + final entry = attentionEntryFor(run); + if (entry == null || dismissed.contains(entry.key)) continue; + if (since != null && + since.millisecondsSinceEpoch > 0 && + _before(entry.recency, since)) { + continue; + } + entries.add(entry); + } + entries.sort((a, b) { + final rank = a.kind.rank.compareTo(b.kind.rank); + if (rank != 0) return rank; + final recency = b.recency.compareTo(a.recency); + return recency != 0 ? recency : b.runId.compareTo(a.runId); + }); + return entries; +} + +/// Captures what the surface showed when it opened. Clear all acts on this +/// snapshot, so an entry that arrives later is not silently removed. +List attentionDismissalSnapshot( + Iterable entries, +) => List.unmodifiable(entries); + +/// Adds one identity, ignoring a blank or already-present key. +Set attentionDismiss(Set dismissed, String key) { + final next = {...dismissed}; + if (key.trim().isNotEmpty) next.add(key); + return next; +} + +/// Unions exactly the snapshot's identities. Entries that arrived after the +/// snapshot was taken are left alone. +Set attentionDismissAll( + Set dismissed, + Iterable snapshot, +) { + final next = {...dismissed}; + for (final entry in snapshot) { + next.add(entry.key); + } + return next; +} + +/// The one-line JSON a dismissed set is stored as: a sorted array of strings, so +/// an unchanged set always encodes to the same bytes. +String encodeAttentionDismissals(Set dismissed) { + final keys = dismissed.where((key) => key.isNotEmpty).toList()..sort(); + return jsonEncode(keys); +} + +/// Decodes a stored value into a dismissed set. Total: blank text, unreadable +/// JSON, a non-array value and non-string members all decode to the members we +/// can read, and a malformed value never throws. +Set decodeAttentionDismissals(String? stored) { + final text = (stored ?? '').trim(); + if (text.isEmpty) return {}; + dynamic parsed; + try { + parsed = jsonDecode(text); + } catch (_) { + return {}; + } + if (parsed is! List) return {}; + return { + for (final value in parsed) + if (value is String && value.isNotEmpty) value, + }; +} + +String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase(); + +bool _positive(dynamic value) { + final number = value is num ? value : num.tryParse('${value ?? ''}'.trim()); + return (number ?? 0) > 0; +} + +/// True only when [recency] is a readable timestamp before [cutoff]. An +/// unparseable or blank timestamp is not filtered out, matching the browser. +bool _before(String recency, DateTime cutoff) { + final at = DateTime.tryParse(recency.trim()); + return at != null && at.isBefore(cutoff); +} diff --git a/app/lib/features/attention/domain/attention_transitions.dart b/app/lib/features/attention/domain/attention_transitions.dart new file mode 100644 index 00000000..8876ef40 --- /dev/null +++ b/app/lib/features/attention/domain/attention_transitions.dart @@ -0,0 +1,136 @@ +import '../../../core/api_gateway.dart'; +import 'attention_models.dart'; + +/// One newly-entered attention state: a run that has just become failed or has +/// just become a human decision. The entry carries the whole current summary, so +/// its wording and unknown fields match what the surface would show. +class AttentionTransition { + const AttentionTransition(this.entry); + + final AttentionEntry entry; + + int get runId => entry.runId; + AttentionKind get kind => entry.kind; + String get key => entry.key; + JsonMap get run => entry.run; +} + +/// Tracks the last status seen for each run and emits only a genuine transition +/// *into* a qualifying state. +/// +/// - [seed] records the authoritative list (the initial `list_runs` read or a +/// `subscribe` snapshot) without emitting anything, so a run that was already +/// failed/waiting before this client looked never announces itself. +/// - [beginSeed]/[endSeed] bracket a reconnect's pushed snapshot: frames seen +/// while seeding update the baseline but raise nothing, so a gap can never +/// manufacture a transition. +/// - [observe] emits only when a known run's status changes into `failed` or a +/// human `waiting`. A duplicate frame, an unchanged qualifying state, an +/// unknown/nonqualifying status and a first-seen run all return null. +/// - A run+kind key is forgotten when the run leaves that qualifying state (or +/// enters the other kind), so a genuinely new transition can fire once more; +/// the same transition can never repeat. +/// - [resetForReconnect] drops the status baseline but keeps the emitted keys. +/// The following [reseed] establishes the new baseline without emitting, so a +/// disconnect cannot produce a delayed notification for a state the operator +/// already saw. +class AttentionTransitionDetector { + final Map _lastStatus = {}; + final Set _emitted = {}; + bool _seeding = false; + + /// Records [runs] as the baseline without emitting. Keys that still qualify + /// are kept so a reconnect cannot repeat them; keys whose run disappeared from + /// the read are kept too, because an absent run tells us nothing. + void seed(Iterable? runs) { + final statuses = {}; + final kinds = {}; + for (final run in runs ?? const []) { + final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']); + if (runId == null) continue; + statuses[runId] = _word(run['status']); + kinds[runId] = attentionKindForRun(run); + } + _lastStatus + ..clear() + ..addAll(statuses); + for (final key in [..._emitted]) { + final split = key.lastIndexOf(':'); + if (split <= 0) continue; + final runId = attentionRunId(key.substring(0, split)); + if (runId == null || !statuses.containsKey(runId)) continue; + final kind = kinds[runId]; + if (kind == null || key != attentionKey(runId, kind)) { + _emitted.remove(key); + } + } + } + + /// Replaces the baseline for a reconnect. Emitted keys survive: a transition + /// swallowed by the gap is not replayed after the socket returns. + void reseed(Iterable? runs) { + _lastStatus.clear(); + _seeding = false; + seed(runs); + } + + /// Drops the status baseline but keeps this session's emitted keys. Call + /// before the next [seed] when the connection is lost. + void resetForReconnect() { + _lastStatus.clear(); + _seeding = false; + } + + void beginSeed() => _seeding = true; + + void endSeed() => _seeding = false; + + /// Observes one pushed `run_event` summary/frame. Returns the transition only + /// when this run enters a qualifying state; [dismissed] identities are marked + /// seen but do not emit. + AttentionTransition? observe( + JsonMap frame, { + Set dismissed = const {}, + }) { + final runId = + attentionRunId(frame['run_id']) ?? attentionRunId(frame['id']); + final status = _word(frame['status']); + if (runId == null || status.isEmpty) return null; + + final previous = _lastStatus[runId]; + _lastStatus[runId] = status; + + final kind = attentionKindForRun(frame); + if (kind == null) { + _forget(runId); + return null; + } + for (final other in AttentionKind.values) { + if (other != kind) _emitted.remove(attentionKey(runId, other)); + } + if (_seeding) return null; + + final key = attentionKey(runId, kind); + if (previous == null || previous == status) return null; + + final entry = attentionEntryFor(frame); + if (entry == null) return null; + _emitted.add(key); + if (dismissed.contains(key)) return null; + return AttentionTransition(entry); + } + + /// A copy of the run+kind identities raised in this session. + Set get emittedKeys => {..._emitted}; + + /// The last status recorded for [runId], or null for a run never seen. + String? statusOf(int runId) => _lastStatus[runId]; + + void _forget(int runId) { + for (final kind in AttentionKind.values) { + _emitted.remove(attentionKey(runId, kind)); + } + } +} + +String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase(); diff --git a/app/notes/R4-attention.md b/app/notes/R4-attention.md new file mode 100644 index 00000000..c8f1cbce --- /dev/null +++ b/app/notes/R4-attention.md @@ -0,0 +1,61 @@ +# Attention model (pure domain) + +The `Needs you` model exists as reusable, widget-free Dart under +`lib/features/attention/domain/`. The list, identity, wording and local-day +window mirror the browser's `src/attention.js`; no UI, storage plugin, +notification permission or API request is added here. + +`attention_transitions.dart` is an attention transition ledger, not a port of +`src/notify.js`: notification permission, tray alerts, `notify_mode` suppression +and success alerts are deliberately outside this slice. + +- `attention_models.dart` owns the two kinds (`Decision` rank 0, `Failed` rank 1), + qualification, ordered entries, labels/detail wording, `{runId}:{kind}` + identities, dismissal/snapshot bookkeeping and the JSON string-array + serialisation under `pipelines.web.attention.v1`. +- Only `waiting` and `failed` statuses qualify, after trimming/lowercasing. A + waiting run with a session audit/export handoff (`export_pending_sequence > 0`) + asks no person and is excluded; a failed run stays failed. `resource_wait` is + deliberately not consulted, matching `web/src/attention.js` and `Attention.kt` + (the server retired the field, and a stale value must not hide a decision). +- The surface is today's work: `attentionEntries` accepts an optional `since` + cutoff and drops an entry when its recency parses and is before it, keeping a + blank or unreadable recency, exactly as the browser does. No cutoff (or an + epoch-zero one) shows everything. Callers pass `startOfLocalDay()` to the bell, + the sheet and the Clear-all snapshot, so yesterday's failures become history. + Stored dismissals themselves still never expire. +- `startOfLocalDay({now})` returns local midnight and takes an injectable `now` + so the UI does not re-derive it and tests stay deterministic. +- Ordering is kind rank, then `finished_at` else `created_at` descending using the + server's timestamp text, then run id descending. The label is the trimmed title + else pipeline name; the detail is `Waiting for your decision`, or the trimmed + diagnostic else `Run failed`. +- Entries retain the whole source summary map, so fields this model does not read + (and unknown future fields) are preserved. `AttentionEntry` is constructed only + by `attentionEntryFor`, so its `runId` is always a validated positive id. +- `attention_transitions.dart` is a pure detector: a seed/first-seen run, + duplicate frame, nonqualifying status, export wait, reconnect reseed or a + snapshot bracketed with `beginSeed`/`endSeed` never emits. It emits once when a + known run enters `failed` or a human `waiting`, forgets the key when the run + leaves that state, and keeps the emitted set across `resetForReconnect`/`reseed` + so a gap cannot replay a transition. A reseed keeps the key of a run that still + qualifies (or that is absent from the read) and prunes one whose run no longer + asks. Dismissed identities are marked seen but suppressed. + +Focused tests in `test/features/attention/` cover qualification and exclusions, +ordering and tie-breaks, the local-day cutoff (older/newer, unparseable/blank +recency, no cutoff, decisions, dismissal composition), wording/labels, identity, +dismissal filtering, the clear-all snapshot, defensive copying, malformed/blank +storage, unknown-field preservation, and transition dedupe/first-seen/ +nonqualifying/reconnect reseed/emitted-key retention. + +Verification: `flutter test test/features/attention` passed all 44 tests; +`flutter analyze` reported no issues. No browser capture applies to this +nonvisual domain slice. + +Not done here: no `Needs you` screen/sheet, badge, storage write, store/controller +wiring or notification permission was added, and `PARITY.md` remains `Missing` +until those land. The older `orderAttention` helper in +`lib/features/runs/domain/run_models.dart` was left untouched for lane ownership; +the runs UI must delegate to this model when it is wired, so the two authorities +cannot diverge. Mobile is unverified. diff --git a/app/test/features/attention/attention_dismissals_test.dart b/app/test/features/attention/attention_dismissals_test.dart new file mode 100644 index 00000000..c2bf2942 --- /dev/null +++ b/app/test/features/attention/attention_dismissals_test.dart @@ -0,0 +1,113 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; + +Map run([Map overrides = const {}]) => { + 'id': 1, + 'name': 'Plan and land', + 'title': null, + 'status': 'failed', + 'created_at': '2026-10-19T10:00:00Z', + 'finished_at': '2026-10-19T10:05:00Z', + 'diagnostic': '', + ...overrides, +}; + +void main() { + group('dismissal and clear-all snapshot', () { + test('a dismissed identity is filtered out and never returns', () { + final rows = [ + run({'id': 7, 'status': 'waiting', 'title': 'Wait'}), + ]; + final dismissed = attentionDismiss(const {}, '7:Decision'); + expect(attentionEntries(rows, dismissed: dismissed), isEmpty); + expect(attentionEntries(rows, dismissed: dismissed), isEmpty); + }); + + test('a different kind for the same run is a different identity', () { + final dismissed = attentionDismiss(const {}, '7:Decision'); + final failed = run({'id': 7, 'status': 'failed', 'diagnostic': 'later'}); + final entries = attentionEntries([failed], dismissed: dismissed); + expect(entries.single.key, '7:Failed'); + expect(entries.single.detail, 'later'); + }); + + test('dismiss ignores a blank key and adds once', () { + final one = attentionDismiss(const {}, '1:Failed'); + expect(one, {'1:Failed'}); + expect(attentionDismiss(one, '1:Failed'), {'1:Failed'}); + expect(attentionDismiss(one, ' '), {'1:Failed'}); + expect(one, {'1:Failed'}, reason: 'input set is not mutated'); + }); + + test('clear all applies only the identities in the open snapshot', () { + final a = attentionEntryFor(run({'id': 1}))!; + final snapshot = attentionDismissalSnapshot([a]); + final b = attentionEntryFor(run({'id': 2}))!; + final after = attentionDismissAll(const {}, snapshot); + expect(after, {'1:Failed'}); + expect(after.contains(b.key), isFalse); + expect( + attentionEntries([ + run({'id': 1}), + run({'id': 2}), + ], dismissed: after).map((entry) => entry.runId), + [2], + ); + }); + + test('the snapshot is a defensive copy', () { + final a = attentionEntryFor(run({'id': 1}))!; + final b = attentionEntryFor(run({'id': 2}))!; + final live = [a, b]; + final snapshot = attentionDismissalSnapshot(live); + live.add(attentionEntryFor(run({'id': 3}))!); + expect(snapshot.map((entry) => entry.runId), [1, 2]); + expect(snapshot, isNot(same(live))); + }); + }); + + group('persistence', () { + test('the key is the documented one', () { + expect(attentionStorageKey, 'pipelines.web.attention.v1'); + }); + + test('encoding is one sorted JSON array and round-trips', () { + final encoded = encodeAttentionDismissals({ + '9:Failed', + '1:Decision', + '4:Failed', + }); + expect(encoded, '["1:Decision","4:Failed","9:Failed"]'); + expect(decodeAttentionDismissals(encoded), { + '1:Decision', + '4:Failed', + '9:Failed', + }); + expect(encodeAttentionDismissals(const {}), '[]'); + }); + + test('blank or unreadable storage decodes to empty and never throws', () { + for (final stored in [ + null, + '', + ' ', + 'not json', + '{', + '"a string"', + '{}', + '42', + ]) { + expect(decodeAttentionDismissals(stored), isEmpty); + } + }); + + test('a JSON array keeps only non-empty strings', () { + expect( + decodeAttentionDismissals( + '["1:Failed", 2, null, {"a":1}, "3:Decision", ""]', + ), + {'1:Failed', '3:Decision'}, + ); + }); + }); +} diff --git a/app/test/features/attention/attention_models_test.dart b/app/test/features/attention/attention_models_test.dart new file mode 100644 index 00000000..bc3ba0c8 --- /dev/null +++ b/app/test/features/attention/attention_models_test.dart @@ -0,0 +1,334 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; + +Map run([Map overrides = const {}]) => { + 'id': 1, + 'name': 'Plan and land', + 'title': null, + 'status': 'failed', + 'created_at': '2026-10-19T10:00:00Z', + 'finished_at': '2026-10-19T10:05:00Z', + 'diagnostic': '', + ...overrides, +}; + +void main() { + group('qualification', () { + test('only waiting and failed qualify; every other status asks nobody', () { + expect(attentionKindOf('waiting'), AttentionKind.decision); + expect(attentionKindOf('failed'), AttentionKind.failed); + for (final status in [ + 'queued', + 'running', + 'succeeded', + 'canceled', + 'cancelled', + 'interrupted', + 'active', + 'blocked', + 'skipped', + 'unknown', + '', + ' ', + null, + 'FAILED?', + ]) { + expect( + attentionKindOf(status), + isNull, + reason: 'status ${status ?? 'null'} must not qualify', + ); + } + }); + + test('trims and lowercases the server words', () { + expect(attentionKindOf(' Waiting '), AttentionKind.decision); + expect(attentionKindOf('Failed\n'), AttentionKind.failed); + expect(attentionKindOf('WAITING'), AttentionKind.decision); + }); + + test('ranks are Decision 0 then Failed 1', () { + expect(AttentionKind.decision.rank, 0); + expect(AttentionKind.failed.rank, 1); + }); + + test('waiting excludes audit/export handoffs, not resource waits', () { + expect( + attentionKindForRun(run({'status': 'waiting'})), + AttentionKind.decision, + ); + expect( + attentionKindForRun( + run({'status': 'waiting', 'export_pending_sequence': 4}), + ), + isNull, + ); + expect( + attentionKindForRun( + run({'status': 'waiting', 'export_pending_sequence': ' 2 '}), + ), + isNull, + ); + expect( + attentionKindForRun( + run({'status': 'waiting', 'export_pending_sequence': 0}), + ), + AttentionKind.decision, + ); + // web/src/attention.js and Attention.kt never consult resource_wait; the + // server retired it, so a stale value must not hide a real decision. + for (final stale in [ + {'resource': 'device-1'}, + 'device-1', + true, + 1, + ]) { + expect( + attentionKindForRun( + run({'status': 'waiting', 'resource_wait': stale}), + ), + AttentionKind.decision, + reason: 'resource_wait $stale must not suppress a decision', + ); + } + // A failed run stays failed even if a stale export field survived. + expect( + attentionKindForRun( + run({'status': 'failed', 'export_pending_sequence': 4}), + ), + AttentionKind.failed, + ); + }); + + test( + 'nonqualifying runs are dropped entirely, including malformed ids', + () { + final entries = attentionEntries([ + run({'id': 1, 'status': 'succeeded'}), + run({'id': 2, 'status': 'running'}), + run({'id': 3, 'status': 'failed'}), + run({'id': 4, 'status': 'queued'}), + run({'id': 'not-a-number', 'status': 'failed'}), + run({'id': 0, 'status': 'failed'}), + ]); + expect(entries.map((entry) => entry.runId), [3]); + expect(attentionEntries(null), isEmpty); + }, + ); + }); + + group('identity and wording', () { + test('identity is exactly {runId}:{kind}', () { + expect(attentionKey(440, AttentionKind.failed), '440:Failed'); + expect(attentionKey(12, AttentionKind.decision), '12:Decision'); + }); + + test('label is the trimmed title else the pipeline name', () { + expect(attentionEntryFor(run({'title': ' My run '}))!.label, 'My run'); + expect(attentionEntryFor(run({'title': ' '}))!.label, 'Plan and land'); + expect(attentionEntryFor(run({'title': null}))!.label, 'Plan and land'); + }); + + test( + 'detail is the decision line or the trimmed diagnostic else Run failed', + () { + expect( + attentionDetail(AttentionKind.decision, run({'status': 'waiting'})), + 'Waiting for your decision', + ); + expect( + attentionDetail( + AttentionKind.failed, + run({'diagnostic': ' boom '}), + ), + 'boom', + ); + expect( + attentionDetail(AttentionKind.failed, run({'diagnostic': ' '})), + 'Run failed', + ); + expect( + attentionDetail(AttentionKind.failed, run({'diagnostic': null})), + 'Run failed', + ); + }, + ); + + test('row description is exactly {pipeline} · {detail}', () { + final entry = attentionEntryFor( + run({'title': 'T', 'diagnostic': 'failed hard'}), + )!; + expect(attentionRowDescription(entry), 'Plan and land · failed hard'); + }); + + test('badge label is bare Notifications when empty, else the count', () { + expect(attentionBadgeLabel(0), 'Notifications'); + expect(attentionBadgeLabel(-3), 'Notifications'); + expect(attentionBadgeLabel(1), 'Notifications, 1 needing attention'); + expect(attentionBadgeLabel(171), 'Notifications, 171 needing attention'); + }); + + test('the entry keeps the whole summary, including unknown fields', () { + final source = run({ + 'unknown_future_field': {'keep': true}, + 'id': 7, + }); + final entry = attentionEntryFor(source)!; + expect(entry.run['unknown_future_field'], {'keep': true}); + expect(entry.run, same(source)); + }); + }); + + group('ordering', () { + test('kind rank, then recency descending, then run id descending', () { + final entries = attentionEntries([ + run({ + 'id': 10, + 'status': 'failed', + 'finished_at': '2026-10-19T10:00:00Z', + }), + run({ + 'id': 11, + 'status': 'waiting', + 'finished_at': '2026-10-19T09:00:00Z', + }), + run({ + 'id': 12, + 'status': 'failed', + 'finished_at': '2026-10-19T11:00:00Z', + }), + run({ + 'id': 13, + 'status': 'waiting', + 'finished_at': '2026-10-19T08:00:00Z', + }), + ]); + expect(entries.map((entry) => entry.runId), [11, 13, 12, 10]); + }); + + test('recency falls back to created_at when finished_at is blank', () { + final entries = attentionEntries([ + run({ + 'id': 1, + 'status': 'failed', + 'finished_at': '', + 'created_at': '2026-10-19T12:00:00Z', + }), + run({ + 'id': 2, + 'status': 'failed', + 'finished_at': '2026-10-19T11:00:00Z', + }), + ]); + expect(entries.map((entry) => entry.runId), [1, 2]); + }); + + test('equal kind and recency tie by run id descending and stay stable', () { + final rows = [ + run({'id': 3, 'finished_at': '2026-10-19T10:00:00Z'}), + run({'id': 9, 'finished_at': '2026-10-19T10:00:00Z'}), + run({'id': 5, 'finished_at': '2026-10-19T10:00:00Z'}), + ]; + expect(attentionEntries(rows).map((entry) => entry.runId), [9, 5, 3]); + expect(attentionEntries(rows.reversed).map((entry) => entry.runId), [ + 9, + 5, + 3, + ]); + }); + }); + + group('local-day window', () { + final since = DateTime.utc(2026, 10, 20); + final rows = [ + run({'id': 1, 'finished_at': '2026-10-19T21:33:27Z'}), + run({'id': 2, 'finished_at': '2026-10-20T10:00:00Z'}), + ]; + + test('startOfLocalDay is local midnight, injectable for tests', () { + final now = DateTime(2026, 10, 20, 15, 4, 5, 6); + final start = startOfLocalDay(now: now); + expect(start, DateTime(2026, 10, 20)); + expect(start.hour, 0); + expect(start.minute, 0); + expect(start.second, 0); + expect(start.millisecond, 0); + expect(start.isBefore(now), isTrue); + expect(start.toLocal(), start); + }); + + test('a cutoff drops older work and keeps newer work', () { + expect(attentionEntries(rows, since: since).map((entry) => entry.runId), [ + 2, + ]); + }); + + test('no cutoff, and an epoch-zero cutoff, show everything', () { + expect(attentionEntries(rows).map((entry) => entry.runId), [2, 1]); + expect( + attentionEntries( + rows, + since: DateTime.fromMillisecondsSinceEpoch(0), + ).map((entry) => entry.runId), + [2, 1], + ); + }); + + test('the cutoff applies to waiting decisions as well as failures', () { + expect( + attentionEntries([ + run({ + 'id': 3, + 'status': 'waiting', + 'finished_at': '2026-10-19T09:00:00Z', + }), + ], since: since), + isEmpty, + ); + }); + + test('unparseable or blank recency is kept, as in the browser', () { + for (final recency in ['', ' ', 'not a timestamp']) { + final kept = attentionEntries([ + run({'id': 4, 'finished_at': recency, 'created_at': recency}), + ], since: since); + expect( + kept.map((entry) => entry.runId), + [4], + reason: 'recency ${recency.isEmpty ? '' : recency} is kept', + ); + } + }); + + test('finished_at is the recency the cutoff reads, else created_at', () { + expect( + attentionEntries([ + run({ + 'id': 5, + 'created_at': '2026-10-18T09:00:00Z', + 'finished_at': '2026-10-20T09:00:00Z', + }), + ], since: since).map((entry) => entry.runId), + [5], + ); + expect( + attentionEntries([ + run({ + 'id': 6, + 'created_at': '2026-10-18T09:00:00Z', + 'finished_at': '', + }), + ], since: since), + isEmpty, + ); + }); + + test('dismissal and the cutoff compose', () { + final dismissed = attentionDismiss(const {}, '2:Failed'); + expect( + attentionEntries(rows, dismissed: dismissed, since: since), + isEmpty, + ); + }); + }); +} diff --git a/app/test/features/attention/attention_transitions_test.dart b/app/test/features/attention/attention_transitions_test.dart new file mode 100644 index 00000000..a63da11e --- /dev/null +++ b/app/test/features/attention/attention_transitions_test.dart @@ -0,0 +1,224 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/domain/attention_transitions.dart'; + +Map run([Map overrides = const {}]) => { + 'id': 1, + 'name': 'Plan and land', + 'title': null, + 'status': 'failed', + 'created_at': '2026-10-19T10:00:00Z', + 'finished_at': '2026-10-19T10:05:00Z', + 'diagnostic': '', + ...overrides, +}; + +void main() { + test('a seeded failed/waiting run raises nothing', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 1, 'status': 'failed'}), + run({'id': 2, 'status': 'waiting'}), + ]); + expect(detector.observe(run({'id': 1, 'status': 'failed'})), isNull); + expect(detector.observe(run({'id': 2, 'status': 'waiting'})), isNull); + expect(detector.emittedKeys, isEmpty); + }); + + test('a first-seen run raises nothing and becomes the baseline', () { + final detector = AttentionTransitionDetector(); + expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull); + expect(detector.statusOf(5), 'failed'); + expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull); + expect(detector.emittedKeys, isEmpty); + }); + + test('entering failed from a known running run emits exactly once', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 5, 'status': 'running'}), + ]); + final first = detector.observe(run({'id': 5, 'status': 'failed'})); + expect(first, isNotNull); + expect(first!.runId, 5); + expect(first.kind, AttentionKind.failed); + expect(first.key, '5:Failed'); + expect(first.entry.label, 'Plan and land'); + expect(first.entry.detail, 'Run failed'); + + expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull); + expect(detector.emittedKeys, {'5:Failed'}); + }); + + test('entering a human waiting state emits a Decision', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 6, 'status': 'running'}), + ]); + final transition = detector.observe( + run({'id': 6, 'status': 'waiting', 'title': ' Decide '}), + ); + expect(transition, isNotNull); + expect(transition!.kind, AttentionKind.decision); + expect(transition.key, '6:Decision'); + expect(transition.entry.label, 'Decide'); + expect(transition.entry.detail, 'Waiting for your decision'); + }); + + test('waiting to failed is a new kind and emits once', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 7, 'status': 'waiting'}), + ]); + final transition = detector.observe(run({'id': 7, 'status': 'failed'})); + expect(transition!.key, '7:Failed'); + expect(detector.emittedKeys, {'7:Failed'}); + }); + + test('a run that leaves the state and returns may emit again', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 8, 'status': 'running'}), + ]); + expect(detector.observe(run({'id': 8, 'status': 'failed'})), isNotNull); + expect(detector.observe(run({'id': 8, 'status': 'running'})), isNull); + expect(detector.emittedKeys, isEmpty); + final again = detector.observe(run({'id': 8, 'status': 'failed'})); + expect(again, isNotNull); + expect(detector.observe(run({'id': 8, 'status': 'failed'})), isNull); + }); + + test('nonqualifying statuses never emit', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 9, 'status': 'queued'}), + ]); + for (final status in [ + 'running', + 'succeeded', + 'canceled', + 'interrupted', + 'unknown', + ]) { + expect( + detector.observe(run({'id': 9, 'status': status})), + isNull, + reason: 'status $status must not emit', + ); + } + expect(detector.emittedKeys, isEmpty); + }); + + test( + 'an export wait never emits a Decision even though status is waiting', + () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 10, 'status': 'running'}), + ]); + expect( + detector.observe( + run({'id': 10, 'status': 'waiting', 'export_pending_sequence': 2}), + ), + isNull, + ); + expect(detector.emittedKeys, isEmpty); + }, + ); + + test('dismissed identities are marked seen but do not emit', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 11, 'status': 'running'}), + ]); + expect( + detector.observe( + run({'id': 11, 'status': 'failed'}), + dismissed: {'11:Failed'}, + ), + isNull, + ); + expect(detector.emittedKeys, {'11:Failed'}); + expect(detector.observe(run({'id': 11, 'status': 'failed'})), isNull); + }); + + test('a reconnect reseed produces no transition and no replay', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 12, 'status': 'failed'}), + ]); + detector.resetForReconnect(); + detector.reseed([ + run({'id': 12, 'status': 'failed'}), + ]); + expect(detector.observe(run({'id': 12, 'status': 'failed'})), isNull); + expect(detector.emittedKeys, isEmpty); + }); + + test('a reseed keeps still-qualifying keys and prunes the rest', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 20, 'status': 'running'}), + run({'id': 21, 'status': 'running'}), + ]); + expect(detector.observe(run({'id': 20, 'status': 'failed'})), isNotNull); + expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNotNull); + expect(detector.emittedKeys, {'20:Failed', '21:Decision'}); + + detector.reseed([ + run({'id': 20, 'status': 'failed'}), + run({'id': 21, 'status': 'succeeded'}), + ]); + // 20 still qualifies, so its key survives; 21 no longer asks, so its key is + // pruned and a genuine later transition can be raised once more. + expect(detector.emittedKeys, {'20:Failed'}); + expect(detector.observe(run({'id': 20, 'status': 'failed'})), isNull); + expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNotNull); + expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNull); + }); + + test('a reseed keeps the key of a run absent from the read', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 22, 'status': 'running'}), + ]); + expect(detector.observe(run({'id': 22, 'status': 'failed'})), isNotNull); + + detector.reseed([ + run({'id': 23, 'status': 'running'}), + ]); + expect(detector.emittedKeys, {'22:Failed'}); + // Absence says nothing, so seeing the same state again is not a transition. + expect(detector.observe(run({'id': 22, 'status': 'failed'})), isNull); + }); + + test('a snapshot bracketed as a seed does not emit or replay', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 13, 'status': 'running'}), + ]) + ..beginSeed(); + expect(detector.observe(run({'id': 13, 'status': 'waiting'})), isNull); + detector.endSeed(); + expect(detector.observe(run({'id': 13, 'status': 'waiting'})), isNull); + expect(detector.emittedKeys, isEmpty); + }); + + test('the transition keeps the whole frame, including unknown fields', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 14, 'status': 'running'}), + ]); + final frame = run({ + 'id': 14, + 'run_id': 14, + 'status': 'failed', + 'diagnostic': ' boom ', + 'unknown_future_field': ['keep'], + }); + final transition = detector.observe(frame); + expect(transition!.entry.detail, 'boom'); + expect(transition.run, same(frame)); + expect(transition.run['unknown_future_field'], ['keep']); + }); +} From 78ad636f83f2d4f6f9faff3c6d388afd5c4f67cb Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:16:50 +0100 Subject: [PATCH 11/17] docs(app): record template, schedule and Changes verification state --- app/PARITY.md | 2 +- app/WORK.md | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/app/PARITY.md b/app/PARITY.md index e27822da..2403b355 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -35,7 +35,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Human decisions | Preview waiting card/native prompt/exact accepted reply | attention/action URL entry; no production decision answered during tests | | Run graph | Source projection/visits; definition canvas landed | executed/unvisited routes, live activity, graph clicks open latest RECORDED visit, no definition by default | | Timeline/recorded visit pane | Preview text rows only; authored pane77 | visit selection, status/outcome/duration/model/target/verdict, artifacts/session/input/output/definition tabs | -| Changes/diffs | Preview via run detail | settled-run aggregate gate rechecked in shell; per-visit capture entry still separate | +| Changes/diffs | Preview via run detail | settled-run aggregate gate, recorded file/diff/close/back verified in the real app; per-visit capture entry and paging remain | | Artifact groups | Source model/list | actual visit/run gallery integration and truthful unavailable capture facts | | Artifact preview | Missing | image-primary in-app viewer, video/doc/text/markdown, paging, focus/back, authenticated fetch errors | | Artifact actions | Source safe URL resolution | separate external-open/copy/download; SHARE REAL NAMED MIME FILES, not links; slow activation/cancel/errors | diff --git a/app/WORK.md b/app/WORK.md index 8730b539..940501c6 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -96,6 +96,30 @@ override, server edit or shell-write bypass was used by the manager. Allowed pipeline models: Luna or DeepSeek V4.1 Flash; current runs use Luna. ## Latest integration check +Templates gallery76 landed after inspection: 38 template tests pass, and the +in-process fixture probe passed 7 checks with 7 captures; the selected-template +capture shows metadata, verbatim source and the native create action under one +bar. Schedule form78 and its lossless draft are also in main; the form probe passed +every step with 7 captures and both the Cupertino dark and 320px/2x Material +captures were inspected. Two native-default violations were then removed from the +schedule surfaces: secondary metadata used a hard-coded 14px Cupertino size, and +row titles/statuses forced weights the host already defines. They now use the +host's own text roles. + +The real-app browser probe was extended to exercise the newly wired Changes action +end to end: run detail → recorded file → rendered diff with the exact added/removed +lines → close → back to the same detail. It passes with 30 captures; the diff +capture was inspected. Earlier assertions that indexed captures numerically were +replaced with named capture variables so inserted evidence cannot silently shift +an OCR check. + +Integrated main after these landings:718 tests pass; analysis clean; normal web +build passed; full normal-app probe 30 captures. Published that verified bundle +(rollback build/web-before-full-1792617308). The JS hash is unchanged from the +previous publication because Templates, schedules and their probes are not yet +reachable from shell routes and are tree-shaken; that is expected, not evidence of +a missing build. + The user directs continued work until the whole client is ported, not just components. app/PARITY.md now enumerates the entire remaining behavior inventory against latest web behavior, distinguishing preview/source/active/missing. From 224f8eec074ef3e643dc3176b0599017f924d584 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:17:20 +0100 Subject: [PATCH 12/17] fix(app): keep attention dismissals in this client's own storage namespace --- app/lib/features/attention/domain/attention_models.dart | 9 +++++---- app/notes/R4-attention.md | 3 ++- .../features/attention/attention_dismissals_test.dart | 3 ++- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/app/lib/features/attention/domain/attention_models.dart b/app/lib/features/attention/domain/attention_models.dart index 0f89d2cc..6381b86d 100644 --- a/app/lib/features/attention/domain/attention_models.dart +++ b/app/lib/features/attention/domain/attention_models.dart @@ -21,10 +21,11 @@ enum AttentionKind { final String wireName; } -/// The local storage key shared with the browser client: one JSON array of -/// `{runId}:{kind}` strings. A stored dismissal itself never expires; the -/// surface's local-day window is applied when entries are read, not here. -const attentionStorageKey = 'pipelines.web.attention.v1'; +/// This client's own storage key, namespaced like the rest of the app +/// (`pipelines.next.*`). The identity format matches the browser's, but a +/// dismissal set is deliberately not shared with the legacy web app: the two +/// clients must never rewrite each other's local state on a shared origin. +const attentionStorageKey = 'pipelines.next.attention.v1'; /// The run id a summary or pushed frame carries, or null when it is malformed. /// The server ids are positive integers; anything else cannot identify an entry. diff --git a/app/notes/R4-attention.md b/app/notes/R4-attention.md index c8f1cbce..873c95d6 100644 --- a/app/notes/R4-attention.md +++ b/app/notes/R4-attention.md @@ -12,7 +12,8 @@ and success alerts are deliberately outside this slice. - `attention_models.dart` owns the two kinds (`Decision` rank 0, `Failed` rank 1), qualification, ordered entries, labels/detail wording, `{runId}:{kind}` identities, dismissal/snapshot bookkeeping and the JSON string-array - serialisation under `pipelines.web.attention.v1`. + serialisation under this app's own `pipelines.next.attention.v1` (deliberately + not the legacy web key, so neither client rewrites the other's local state). - Only `waiting` and `failed` statuses qualify, after trimming/lowercasing. A waiting run with a session audit/export handoff (`export_pending_sequence > 0`) asks no person and is excluded; a failed run stays failed. `resource_wait` is diff --git a/app/test/features/attention/attention_dismissals_test.dart b/app/test/features/attention/attention_dismissals_test.dart index c2bf2942..3d2addd7 100644 --- a/app/test/features/attention/attention_dismissals_test.dart +++ b/app/test/features/attention/attention_dismissals_test.dart @@ -68,7 +68,8 @@ void main() { group('persistence', () { test('the key is the documented one', () { - expect(attentionStorageKey, 'pipelines.web.attention.v1'); + expect(attentionStorageKey, 'pipelines.next.attention.v1'); + expect(attentionStorageKey, isNot('pipelines.web.attention.v1')); }); test('encoding is one sorted JSON array and round-trips', () { From 44886a6b105881edd47f5dd4fbed84c3a41c375f Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:19:18 +0100 Subject: [PATCH 13/17] fix(app): choose search controls from the actual host app class --- app/lib/features/search/search_screen.dart | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/app/lib/features/search/search_screen.dart b/app/lib/features/search/search_screen.dart index 3c2e80ce..adaae3e7 100644 --- a/app/lib/features/search/search_screen.dart +++ b/app/lib/features/search/search_screen.dart @@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../core/api_gateway.dart'; +import '../../ui/adaptive/host.dart'; import 'data/search_repository.dart'; import 'domain/search_controller.dart'; import 'domain/search_models.dart'; @@ -100,12 +101,14 @@ class _SearchScreenState extends State { @override Widget build(BuildContext context) { + // Follow the actual host app class first: a CupertinoApp supplies no + // Material theme, so reading only the platform would pick Material controls + // inside a Cupertino host on macOS/iOS. final cupertino = widget.cupertino ?? - switch (Theme.of(context).platform) { - TargetPlatform.iOS || TargetPlatform.macOS => true, - _ => false, - }; + (usesCupertinoHost(context) || + Theme.of(context).platform == TargetPlatform.iOS || + Theme.of(context).platform == TargetPlatform.macOS); return cupertino ? _cupertinoScreen() : _materialScreen(); } From d88213deb41fffe53a234e486a9cdc9003d15575 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:26:34 +0100 Subject: [PATCH 14/17] feat(app): add native authored stage definition pane --- .../graph/domain/stage_definition.dart | 212 ++++++++++ .../graph/widgets/stage_definition_view.dart | 241 +++++++++++ app/notes/P2-stage.md | 103 +++++ .../graph/domain/stage_definition_test.dart | 159 ++++++++ .../widgets/stage_definition_view_test.dart | 286 +++++++++++++ app/tool/stage_definition_probe.dart | 148 +++++++ app/tool/stage_definition_probe.mjs | 380 ++++++++++++++++++ 7 files changed, 1529 insertions(+) create mode 100644 app/lib/features/graph/domain/stage_definition.dart create mode 100644 app/lib/features/graph/widgets/stage_definition_view.dart create mode 100644 app/notes/P2-stage.md create mode 100644 app/test/features/graph/domain/stage_definition_test.dart create mode 100644 app/test/features/graph/widgets/stage_definition_view_test.dart create mode 100644 app/tool/stage_definition_probe.dart create mode 100644 app/tool/stage_definition_probe.mjs diff --git a/app/lib/features/graph/domain/stage_definition.dart b/app/lib/features/graph/domain/stage_definition.dart new file mode 100644 index 00000000..08680773 --- /dev/null +++ b/app/lib/features/graph/domain/stage_definition.dart @@ -0,0 +1,212 @@ +import 'graph_definition.dart'; +import 'graph_protocol.dart'; + +/// The read-only definition of one declared stage, as field rows. +/// +/// Mirrors `stageDefinitionFields`/`terminalFields` from `web/src/graph.js`: +/// the same labels, the same order, and the same rule that blank fields are +/// omitted rather than shown as an empty row. Pure data only: nothing here +/// reads run visits, so a definition can be inspected without claiming that a +/// stage executed. +class StageDefinitionField { + const StageDefinitionField(this.label, this.value, {this.block = false}); + + final String label; + final String value; + + /// Multi-line content (prompt, output, outcomes, tools, memory, routes). + final bool block; +} + +/// The one stage declaration [key] names, or null when this version does not +/// declare it. +/// +/// The last declaration wins, matching the web pane's `new Map(stages)`. +Map? stageDefinitionFor(dynamic graph, String key) { + final stages = graph is Map ? graph['stages'] : null; + if (stages is! List) return null; + Map? found; + for (final stage in stages) { + if (stage is Map && _text(stage['key']) == key) { + found = Map.from(stage); + } + } + return found; +} + +/// A stage's effective type: a blank/absent type reads `model`, exactly as +/// `effectiveStageType` in `web/src/templates.js`. +String effectiveStageType(dynamic type) { + final text = _text(type); + return text.trim().isEmpty ? 'model' : text; +} + +/// A config key's display label (`configLabel` in `web/src/graph.js`). +String stageConfigLabel(String key) { + switch (key) { + case 'provider': + return 'Provider'; + case 'model': + return 'Model'; + case 'retries': + return 'Retries'; + case 'timeout': + return 'Timeout'; + case 'budget_usd': + return 'Budget (USD)'; + case 'budget_tokens': + return 'Budget (tokens)'; + case 'harness': + return 'Harness'; + default: + return key; + } +} + +/// The definition fields of one stage declaration, in the web pane's order. +/// +/// Only non-blank fields are emitted. Unknown keys are deliberately not +/// interpreted here; the pane keeps the stage's raw JSON so they stay visible. +List stageDefinitionFields(dynamic stage) { + if (stage is! Map) return const []; + final fields = [ + StageDefinitionField('Type', effectiveStageType(stage['type'])), + ]; + + final prompt = _text(stage['prompt']); + if (prompt.trim().isNotEmpty) { + fields.add(StageDefinitionField('Prompt', prompt, block: true)); + } + final output = _text(stage['output']); + if (output.trim().isNotEmpty) { + fields.add(StageDefinitionField('Output', output, block: true)); + } + + final edges = stage['edges']; + final outcomes = []; + for (final outcome in stageOutcomes(stage)) { + final raw = edges is Map ? edges[outcome] : null; + final target = resolveTarget(outcome, raw == null ? '' : _text(raw)) ?? ''; + final suffix = isTerminalTarget(target) ? ' (terminal)' : ''; + outcomes.add('$outcome \u2192 ${nodeLabel(target)}$suffix'); + } + if (outcomes.isNotEmpty) { + fields.add( + StageDefinitionField('Outcomes', outcomes.join('\n'), block: true), + ); + } + + final configs = stage['configs']; + if (configs is Map) { + final entries = configs.entries.toList() + ..sort((a, b) => _text(a.key).compareTo(_text(b.key))); + for (final entry in entries) { + final value = _text(entry.value); + if (entry.value == null || value.trim().isEmpty) continue; + fields.add( + StageDefinitionField(stageConfigLabel(_text(entry.key)), value), + ); + } + } + + final blocks = stage['blocks']; + if (blocks is Map) { + final tools = blocks['tools']; + final text = _text(tools); + if (tools != null && text.trim().isNotEmpty) { + fields.add(StageDefinitionField('Tools', text, block: true)); + } + } + + final limits = stage['limits']; + if (limits is Map) { + final maxVisits = limits['max_visits']; + final visits = maxVisits is num + ? maxVisits + : num.tryParse(_text(maxVisits)); + if (visits != null && visits > 0) { + fields.add(StageDefinitionField('Max visits', _text(maxVisits))); + } + final on = _items(limits['on']); + if (on.isNotEmpty) { + fields.add(StageDefinitionField('Limit on', on.join(', '))); + } + } + + final memory = stage['memory']; + if (memory is Map && memory.isNotEmpty) { + fields.add( + StageDefinitionField( + 'Memory', + [ + for (final entry in memory.entries) + '${_text(entry.key)}: ${_text(entry.value)}', + ].join('\n'), + block: true, + ), + ); + } + + final notify = stage['notify']; + if (notify is Map) { + final on = _items(notify['on']); + if (on.isNotEmpty) { + fields.add(StageDefinitionField('Notify on', on.join(', '))); + } + final destination = _text(notify['destination']); + if (destination.trim().isNotEmpty) { + fields.add(StageDefinitionField('Notify destination', destination)); + } + final artifacts = _items(notify['artifacts']); + if (artifacts.isNotEmpty) { + fields.add( + StageDefinitionField('Notify artifacts', artifacts.join(', ')), + ); + } + } + + return fields; +} + +/// A terminal pane's fields: the declared routes into that target. +/// +/// A terminal is part of the definition, not evidence that a run reached it. +List terminalDefinitionFields(dynamic graph, String key) { + final lines = [ + for (final edge in graphEdges(graph)) + if (edge.target == key) + '${edge.source} \u00b7 ${edge.label} \u2192 ${nodeLabel(key)}', + ]; + return lines.isEmpty + ? const [] + : [ + StageDefinitionField( + 'Incoming routes', + lines.join('\n'), + block: true, + ), + ]; +} + +List _items(dynamic value) { + if (value is! List) return const []; + return [for (final item in value) _text(item)]; +} + +/// Web `String(value)` for the values the definition fields carry. Numbers +/// that are integral render without a trailing `.0`, as JavaScript does; a +/// complex value stays visible but its exact shape is preserved by the raw +/// JSON section instead. +String _text(dynamic value) { + if (value == null) return ''; + if (value is String) return value; + if (value is num) { + if (value.isFinite && + value == value.roundToDouble() && + value.abs() < 1e21) { + return value.toInt().toString(); + } + return value.toString(); + } + return value.toString(); +} diff --git a/app/lib/features/graph/widgets/stage_definition_view.dart b/app/lib/features/graph/widgets/stage_definition_view.dart new file mode 100644 index 00000000..e86a31a1 --- /dev/null +++ b/app/lib/features/graph/widgets/stage_definition_view.dart @@ -0,0 +1,241 @@ +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../domain/graph_protocol.dart'; +import '../domain/stage_definition.dart'; + +/// Wording for a stage that this pinned definition does not declare. +const String unknownStageDefinition = + 'This stage is not declared in this pipeline version. ' + 'No definition has been reconstructed.'; + +/// The web pane's message when a node has no recorded stage or incoming routes. +const String noStageDefinitionDetails = 'No details recorded for this node.'; + +/// Terminals are definition targets; this pane never presents one as evidence. +const String terminalDefinitionNote = + 'Success and Failure are definition targets, not recorded visits. ' + 'This pane shows where the definition routes.'; + +/// The raw section's heading: unknown stage fields stay visible and selectable. +const String rawStageDefinitionTitle = 'Raw stage definition'; + +/// A read-only native view of one stage's declared definition. +/// +/// [graph] is the graph pinned for exactly [pipelineId]/[version] and +/// [stageKey] is a node key (a stage or `#success`/`#failure`). Nothing is +/// fetched and no run visit is read, so the pane cannot imply that the stage +/// executed. Unknown stage declarations get an explicit missing state; every +/// declared stage also keeps its exact JSON below the structured fields. +class StageDefinitionView extends StatelessWidget { + const StageDefinitionView({ + super.key, + required this.graph, + required this.stageKey, + required this.pipelineId, + required this.pipelineName, + required this.version, + }); + + final JsonMap graph; + final String stageKey; + final int pipelineId; + final String pipelineName; + final int version; + + String get _identity => + '${pipelineName.isEmpty ? 'Pipeline' : pipelineName} \u00b7 v$version'; + + @override + Widget build(BuildContext context) { + final style = _StageDefinitionStyle.of(context); + final stage = stageDefinitionFor(graph, stageKey); + final terminal = isTerminalTarget(stageKey); + final fields = stage != null + ? stageDefinitionFields(stage) + : terminal + ? terminalDefinitionFields(graph, stageKey) + : const []; + + return ListView( + padding: const EdgeInsets.all(16), + children: [ + Text(_identity, style: style.muted), + const SizedBox(height: 16), + if (stage == null && !terminal) + Text(unknownStageDefinition, style: style.value) + else ...[ + if (terminal) ...[ + Text(terminalDefinitionNote, style: style.muted), + const SizedBox(height: 16), + ], + for (final field in fields) + _StageDefinitionFieldView(field: field, style: style), + if (terminal && fields.isEmpty) + Text(noStageDefinitionDetails, style: style.muted), + if (stage != null) ...[ + const SizedBox(height: 8), + Text(rawStageDefinitionTitle, style: style.heading), + const SizedBox(height: 8), + _SelectableDefinitionText( + value: const JsonEncoder.withIndent(' ').convert(stage), + style: style.value, + ), + ], + ], + ], + ); + } +} + +/// Opens the platform's native full-screen stage-definition page. +/// +/// The page owns the single navigation bar and its standard back control; the +/// caller only supplies the pinned graph and identity. This is the hook the +/// pipeline graph uses when a node is selected. +Future openStageDefinition( + BuildContext context, { + required JsonMap graph, + required String stageKey, + required int pipelineId, + required String pipelineName, + required int version, +}) { + final view = StageDefinitionView( + graph: graph, + stageKey: stageKey, + pipelineId: pipelineId, + pipelineName: pipelineName, + version: version, + ); + final settings = RouteSettings( + name: 'stage-definition/$pipelineId/$version/$stageKey', + ); + // A terminal is a definition target, not its protocol key: the web pane + // titles it with `nodeDisplayLabel` (`Failure`/`Success`). + final title = '${nodeDisplayLabel(stageKey)} definition'; + final route = usesCupertinoHost(context) + ? CupertinoPageRoute( + settings: settings, + builder: (_) => CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar(middle: Text(title)), + child: SafeArea(child: view), + ), + ) + : MaterialPageRoute( + settings: settings, + builder: (_) => Scaffold( + appBar: AppBar(title: Text(title)), + body: SafeArea(child: view), + ), + ); + return Navigator.of(context).push(route); +} + +/// One labelled field: a compact row for scalars, a selectable block when the +/// value is multi-line authored text. +class _StageDefinitionFieldView extends StatelessWidget { + const _StageDefinitionFieldView({required this.field, required this.style}); + + final StageDefinitionField field; + final _StageDefinitionStyle style; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(field.label, style: style.label), + const SizedBox(height: 4), + if (field.block) + _SelectableDefinitionText(value: field.value, style: style.value) + else + Text(field.value, style: style.value), + ], + ), + ); + } +} + +/// Authored definition text in the host's selectable body. +/// +/// The semantic leaf carries the exact value: Flutter web maps a +/// [SelectableText] to an empty read-only field, so without this a screen +/// reader (and a browser check) sees only its label. The child keeps native +/// pointer selection and the host's system typography. +/// +/// The strut is derived from that same host style and forced, so a glyph the +/// host font lacks (the outcomes arrow `→` is one example) cannot pull in a +/// fallback font with taller metrics and double-space only that block. It is +/// the host's own line metrics, not a font override or a fixed height. +class _SelectableDefinitionText extends StatelessWidget { + const _SelectableDefinitionText({required this.value, required this.style}); + + final String value; + final TextStyle style; + + @override + Widget build(BuildContext context) { + return Semantics( + label: value, + child: ExcludeSemantics( + child: SelectableText( + value, + style: style, + strutStyle: StrutStyle.fromTextStyle(style, forceStrutHeight: true), + ), + ), + ); + } +} + +/// Host text roles only: no palette, font family or explicit size. +class _StageDefinitionStyle { + const _StageDefinitionStyle({ + required this.label, + required this.value, + required this.muted, + required this.heading, + }); + + factory _StageDefinitionStyle.of(BuildContext context) { + if (usesCupertinoHost(context)) { + final theme = CupertinoTheme.of(context); + final secondary = CupertinoColors.secondaryLabel.resolveFrom(context); + return _StageDefinitionStyle( + label: theme.textTheme.tabLabelTextStyle.copyWith(color: secondary), + // SelectableText needs a style it can merge into the default text + // style; Cupertino's textStyle is a complete style with `inherit: false` + // and no baseline. + value: theme.textTheme.textStyle.copyWith(inherit: true), + muted: theme.textTheme.textStyle.copyWith( + inherit: true, + color: secondary, + ), + heading: theme.textTheme.navTitleTextStyle, + ); + } + final theme = Theme.of(context); + return _StageDefinitionStyle( + label: (theme.textTheme.labelMedium ?? const TextStyle()).copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + value: theme.textTheme.bodyMedium ?? const TextStyle(), + muted: (theme.textTheme.bodySmall ?? const TextStyle()).copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + heading: theme.textTheme.titleSmall ?? const TextStyle(), + ); + } + + final TextStyle label; + final TextStyle value; + final TextStyle muted; + final TextStyle heading; +} diff --git a/app/notes/P2-stage.md b/app/notes/P2-stage.md new file mode 100644 index 00000000..36b7b411 --- /dev/null +++ b/app/notes/P2-stage.md @@ -0,0 +1,103 @@ +# P2 stage: read-only definition pane + +The definition graph can now open one stage's authored definition without +reading a run. `StageDefinitionView` receives the graph JsonMap pinned for a +pipeline/version, a stage key and that identity; it performs no request and +shows no visit, status or session data. `openStageDefinition` pushes the +platform's normal page with one navigation bar and its standard back control, +for the manager's graph hook. + +## Behaviour + +- Fields match `stageDefinitionFields`/`terminalFields` in `web/src/graph.js`: + Type, Prompt, Output, Outcomes (ordered, targets resolved, terminals marked), + configs in sorted order with the web labels, Tools, Max visits, Limit on, + Memory, Notify on/destination/artifacts. Only non-blank fields are emitted. +- `effectiveStageType` keeps the web rule that a blank/absent type reads + `model`; no other default is invented. +- A terminal (`#success`/`#failure`) lists its incoming definition routes and + says explicitly that these are definition targets, not recorded visits. Its + page is titled with the web's display label (`Failure definition` / + `Success definition`, via `nodeDisplayLabel`), never the raw `#failure` key. +- A stage key this version does not declare gets an explicit missing state. No + fields, terminal note or raw JSON are fabricated. +- Every declared stage also shows its exact pretty-printed stage JSON in a + selectable raw section, so unknown/future fields stay available. The raw + value is the only source for those keys; the structured rows only interpret + documented ones. +- Host text roles only: Material `Theme`/`ColorScheme`, Cupertino + `CupertinoTheme`/`CupertinoColors`, system fonts, light/dark and text scale + follow the host. No palette, font family, fixed component size or custom + control clone. +- Selectable body blocks force a strut derived from that same host style. + Without it, a glyph the host font lacks (the outcomes arrow `→`) pulls in a + fallback font with taller metrics and doubles only that block's leading. The + strut is the host's own family/size, not a font override or fixed height, and + selection stays native. + +## UI review fixes + +- Cupertino `Outcomes` leading: the block's rendered line pitch matched a + fallback font (34 px between outcome lines against 19 px for `Tools` at 1×, + 68 px against 30 px at 2×). With the forced host strut the line pitch is + 19 px for both blocks at 1× and 37/39 px at 2×, and the semantics block + heights are equal (72/72 at 1×, 123/123 at 2×). The 390×844 / 2× wrap of + `(terminal)` now sits on the same rhythm as the line above it. +- Terminal titles: `#failure definition`/`#success definition` became + `Failure definition`/`Success definition`. The Cupertino widget test now + asserts `Success definition` and the absence of the raw key; a Material + test covers `Failure definition`; the browser probe fails if `#failure` + reappears in the terminal page or if the outcomes/Tools block heights + diverge. + +## Integration dependency + +`PipelineDetail` still has no `graph` field, so the manager's graph hook must +supply the pinned JsonMap it already draws. This item deliberately does not +change the pipeline repository/model. There is no run-mode latest-visit pane +here; recorded visits remain the separate run-graph/audit work. + +## Checks run + +- `flutter test test/features/graph` - 140 tests passed (138 before; two new + regression tests for the terminal title and the forced host strut). +- `flutter analyze` - no issues. +- `dart format --set-exit-if-changed` on the five Dart files - 0 changed. +- `flutter build web` (normal app) - succeeded. +- `flutter build web -t tool/stage_definition_probe.dart` - succeeded. +- `node --check tool/stage_definition_probe.mjs`. +- Real Chrome probe, 1280x900: material dark/light 1x, Cupertino dark/light 1x + and Cupertino dark/light 2x. Each case passed 9 checks and produced 5 + captures. The probe now compares the `Outcomes` and `Tools` semantics block + heights (equal in every case), fails on any raw `#failure` in the terminal + page, asserts `Failure definition`, and scrolls to the pane bottom so the + raw capture really shows `future_field.kept` and `fallback_error`. +- Real Chrome probe, 390x844: Cupertino dark 2x and Material light 1x. Each + passed 8 checks and produced 5 captures, including the `(terminal)` wrap and + the raw JSON at the narrow width. The accent-free rhythm check is skipped at + this width because the outcomes value wraps to three lines. +- Pixel measurement of the final captures: Cupertino 1x outcomes 19 px vs + Tools 19 px (was 34 vs 19); Cupertino 2x outcomes 37 px vs Tools 39 px (was + 68 vs 30); Material 1x outcomes 19 px vs Tools 20 px. + +Captures (under the run's shared artifact folder +`public/stage-definition/`): `--x-{declared,raw,terminal,unknown,closed}.png` +for the six 1280x900 cases, and the same names prefixed with `stage-definition-` +under `narrow-390x844/` for the two 390x844 cases. The raw capture is the real +bottom-scrolled state and its sha1 differs from the declared capture in every +case. + +Mobile (Android/iOS) remains unverified; only web was run. + +## Manager completion after result-validation failure + +Run 77's final Review visit returned no parseable outcome, so the runner retained +its edits and failed the stage without undoing them. No retry was started. The +manager verified the dirty files were the reviewed slice only, ran the focused +domain/view tests (10 pass), and drove the real-browser probe on both hosts: +Material light 1x desktop and Cupertino dark 2x 390x844. Each run passed and +produced five captures (declared, raw, terminal, unknown, closed) under approved +temp/stage-def-browser. The Cupertino dark 2x declared pane was inspected: pinned +identity, wrapping outcome line, native type roles, readable secondary labels. +This remains a definition pane only; run visits and the pipeline graph hook are +separate work. diff --git a/app/test/features/graph/domain/stage_definition_test.dart b/app/test/features/graph/domain/stage_definition_test.dart new file mode 100644 index 00000000..e4b11dd8 --- /dev/null +++ b/app/test/features/graph/domain/stage_definition_test.dart @@ -0,0 +1,159 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/graph/domain/stage_definition.dart'; + +import 'graph_fixtures.dart'; + +JsonMap _stage() => { + 'key': 'build', + 'prompt': 'Implement the planned change.', + 'output': 'A committed change.', + 'edges': { + 'success': 'audit', + 'approved': '#', + 'error': '#failure', + }, + 'fallback_error': true, + 'configs': { + 'provider': 'openai', + 'model': 'gpt-5', + 'budget_usd': 12.5, + 'retries': 2, + 'harness': 'codex', + 'timeout': '15m', + 'skipped_blank': ' ', + 'skipped_null': null, + }, + 'blocks': {'tools': 'shell\nread_file'}, + 'limits': { + 'max_visits': 3, + 'on': ['success', 'error'], + }, + 'memory': {'context': 'latest', 'notes': 'keep'}, + 'notify': { + 'on': ['failure'], + 'destination': 'ops@example.test', + 'artifacts': ['run.log'], + }, + 'custom_flag': true, +}; + +void main() { + group('stage fields', () { + test('follow the web pane order, labels and blank-field rules', () { + final fields = stageDefinitionFields(_stage()); + + expect(fields.map((field) => field.label), [ + 'Type', + 'Prompt', + 'Output', + 'Outcomes', + 'Budget (USD)', + 'Harness', + 'Model', + 'Provider', + 'Retries', + 'Timeout', + 'Tools', + 'Max visits', + 'Limit on', + 'Memory', + 'Notify on', + 'Notify destination', + 'Notify artifacts', + ]); + expect(fields.first.value, 'model'); + expect(fields[1].block, isTrue); + expect(fields[2].value, 'A committed change.'); + expect( + fields[3].value, + 'success → audit\n' + 'approved → SUCCESS (terminal)\n' + 'error → FAILURE (terminal)', + ); + expect(fields[4].value, '12.5'); + expect(fields[5].value, 'codex'); + expect(fields[10].value, 'shell\nread_file'); + expect(fields[11].value, '3'); + expect(fields[12].value, 'success, error'); + expect(fields[13].value, 'context: latest\nnotes: keep'); + expect(fields[14].value, 'failure'); + expect(fields[15].value, 'ops@example.test'); + expect(fields[16].value, 'run.log'); + }); + + test('a blank or absent type reads model; an authored type is kept', () { + expect(effectiveStageType(null), 'model'); + expect(effectiveStageType(' '), 'model'); + expect(effectiveStageType('shell'), 'shell'); + expect( + stageDefinitionFields({'key': 'a'}).single.value, + 'model', + ); + }); + + test('config keys outside the known labels are shown verbatim', () { + final fields = stageDefinitionFields({ + 'key': 'a', + 'configs': {'temperature': 0}, + }); + + expect(fields.map((field) => field.label), contains('temperature')); + expect( + fields.firstWhere((field) => field.label == 'temperature').value, + '0', + ); + }); + + test('zero visits and missing limits emit no invented rows', () { + final fields = stageDefinitionFields({ + 'key': 'a', + 'limits': {'max_visits': 0, 'on': []}, + }); + + expect(fields.map((field) => field.label), ['Type']); + }); + + test( + 'the stage lookup preserves unknown keys and the last declaration', + () { + final graph = { + 'stages': [ + {'key': 'build', 'type': 'old'}, + _stage(), + ], + }; + final stage = stageDefinitionFor(graph, 'build'); + + expect(stage?['type'], isNull); + expect(effectiveStageType(stage?['type']), 'model'); + expect(stage?['custom_flag'], isTrue); + expect(stageDefinitionFor(graph, 'ghost'), isNull); + }, + ); + }); + + group('terminal fields', () { + test('list incoming definition routes, including the fallback marker', () { + expect(terminalDefinitionFields(linearGraph(), '#failure'), hasLength(1)); + final fields = terminalDefinitionFields(linearGraph(), '#failure'); + expect( + fields.single.value, + 'plan · error* → FAILURE\nship · error → FAILURE', + ); + expect(fields.single.block, isTrue); + expect( + terminalDefinitionFields(linearGraph(), '#success').single.value, + 'ship · success → SUCCESS', + ); + }); + + test('a terminal with no routes has no fields to invent', () { + expect( + terminalDefinitionFields({}, '#success'), + isEmpty, + ); + }); + }); +} diff --git a/app/test/features/graph/widgets/stage_definition_view_test.dart b/app/test/features/graph/widgets/stage_definition_view_test.dart new file mode 100644 index 00000000..d226e467 --- /dev/null +++ b/app/test/features/graph/widgets/stage_definition_view_test.dart @@ -0,0 +1,286 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/graph/domain/stage_definition.dart'; +import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart'; + +JsonMap _graph() => { + 'stages': [ + { + 'key': 'plan', + 'type': 'model', + 'prompt': 'Plan the change.', + 'edges': {'success': 'build', 'error': '#'}, + 'fallback_error': true, + 'configs': {'provider': 'openai', 'model': 'gpt-5'}, + 'limits': { + 'max_visits': 2, + 'on': ['error'], + }, + 'future_field': {'kept': true}, + }, + { + 'key': 'build', + 'type': 'shell', + 'edges': {'success': '#success', 'error': '#failure'}, + }, + ], +}; + +Widget _material(Widget child) => MaterialApp( + home: Scaffold( + appBar: AppBar(title: const Text('plan definition')), + body: child, + ), +); + +Widget _cupertino(Widget child, {bool dark = false}) => CupertinoApp( + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + home: CupertinoPageScaffold(child: child), +); + +StageDefinitionView _view({String key = 'plan'}) => StageDefinitionView( + graph: _graph(), + stageKey: key, + pipelineId: 41, + pipelineName: 'Demo pipeline', + version: 7, +); + +/// Finds visible text, including SelectableText's editable body. +Finder _text(String value) => find.byWidgetPredicate( + (widget) => + (widget is Text && widget.data == value) || + (widget is SelectableText && widget.data == value), +); + +void main() { + testWidgets('a declared stage shows pinned identity and web field values', ( + tester, + ) async { + await tester.pumpWidget(_material(_view())); + + expect(_text('Demo pipeline · v7'), findsOneWidget); + expect(_text('model'), findsOneWidget); + expect(_text('Plan the change.'), findsOneWidget); + expect( + _text('success → build\nerror → FAILURE (terminal)'), + findsOneWidget, + ); + expect(_text('Provider'), findsOneWidget); + expect(_text('openai'), findsOneWidget); + expect(_text('Model'), findsOneWidget); + expect(_text('gpt-5'), findsOneWidget); + expect(_text('Max visits'), findsOneWidget); + expect(_text('2'), findsOneWidget); + expect(_text('Limit on'), findsOneWidget); + expect(_text('error'), findsOneWidget); + }); + + testWidgets('the raw section keeps unknown fields exact and selectable', ( + tester, + ) async { + await tester.pumpWidget(_material(_view())); + + expect(_text(rawStageDefinitionTitle), findsOneWidget); + final raw = tester + .widgetList(find.byType(SelectableText)) + .map((widget) => widget.data ?? '') + .join('\n'); + expect(raw, contains('"future_field": {')); + expect(raw, contains('"kept": true')); + expect(raw, contains('"fallback_error": true')); + expect(tester.takeException(), isNull); + }); + + testWidgets('unknown stages get an explicit missing state, never defaults', ( + tester, + ) async { + await tester.pumpWidget(_material(_view(key: 'ghost'))); + + expect(_text(unknownStageDefinition), findsOneWidget); + expect(_text('model'), findsNothing); + expect(_text(rawStageDefinitionTitle), findsNothing); + expect(find.byType(SelectableText), findsNothing); + }); + + testWidgets('terminals explain definition targets and incoming routes', ( + tester, + ) async { + await tester.pumpWidget(_material(_view(key: '#failure'))); + + expect(_text(terminalDefinitionNote), findsOneWidget); + expect(_text('Incoming routes'), findsOneWidget); + expect( + _text('plan · error* → FAILURE\nbuild · error → FAILURE'), + findsOneWidget, + ); + expect(_text(rawStageDefinitionTitle), findsNothing); + expect(_text('successful'), findsNothing); + }); + + testWidgets('Cupertino uses its theme roles in dark mode', (tester) async { + late Color secondary; + await tester.pumpWidget( + _cupertino( + Builder( + builder: (context) { + secondary = CupertinoColors.secondaryLabel.resolveFrom(context); + return _view(); + }, + ), + dark: true, + ), + ); + + final identity = tester.widget(_text('Demo pipeline · v7')); + expect(identity.style?.color, secondary); + expect(_text('Plan the change.'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('the Material helper opens one bar and Back closes it', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => openStageDefinition( + context, + graph: _graph(), + stageKey: 'plan', + pipelineId: 41, + pipelineName: 'Demo pipeline', + version: 7, + ), + child: const Text('Open definition'), + ), + ), + ), + ), + ); + + await tester.tap(find.text('Open definition')); + await tester.pumpAndSettle(); + + expect(_text('plan definition'), findsOneWidget); + expect(find.byType(AppBar), findsOneWidget); + expect(find.byType(BackButton), findsOneWidget); + final route = ModalRoute.of( + tester.element(find.byType(StageDefinitionView)), + ); + expect(route?.settings.name, 'stage-definition/41/7/plan'); + + await tester.pageBack(); + await tester.pumpAndSettle(); + expect(_text('Open definition'), findsOneWidget); + expect(find.byType(StageDefinitionView), findsNothing); + }); + + testWidgets('the Cupertino helper opens one native bar and Back closes it', ( + tester, + ) async { + await tester.pumpWidget( + CupertinoApp( + home: Builder( + builder: (context) => CupertinoPageScaffold( + child: CupertinoButton( + onPressed: () => openStageDefinition( + context, + graph: _graph(), + stageKey: '#success', + pipelineId: 41, + pipelineName: 'Demo pipeline', + version: 7, + ), + child: const Text('Open terminal'), + ), + ), + ), + ), + ); + + await tester.tap(find.text('Open terminal')); + await tester.pumpAndSettle(); + + expect(_text('Success definition'), findsOneWidget); + expect(_text('#success definition'), findsNothing); + expect(find.byType(CupertinoNavigationBar), findsOneWidget); + expect(find.byType(CupertinoNavigationBarBackButton), findsOneWidget); + expect(_text('Incoming routes'), findsOneWidget); + + await tester.tap(find.byType(CupertinoNavigationBarBackButton)); + await tester.pumpAndSettle(); + expect(_text('Open terminal'), findsOneWidget); + expect(find.byType(StageDefinitionView), findsNothing); + }); + + testWidgets('the Material helper titles a terminal with its display label', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => openStageDefinition( + context, + graph: _graph(), + stageKey: '#failure', + pipelineId: 41, + pipelineName: 'Demo pipeline', + version: 7, + ), + child: const Text('Open failure'), + ), + ), + ), + ), + ); + + await tester.tap(find.text('Open failure')); + await tester.pumpAndSettle(); + + expect(_text('Failure definition'), findsOneWidget); + expect(_text('#failure definition'), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('selectable blocks force the host strut for one line rhythm', ( + tester, + ) async { + await tester.pumpWidget(_cupertino(_view())); + + final selectable = tester + .widgetList(find.byType(SelectableText)) + .toList(); + expect(selectable.length, greaterThanOrEqualTo(2)); + for (final widget in selectable) { + final strut = widget.strutStyle; + expect(strut, isNotNull); + // The host's own metrics, forced: a fallback glyph cannot widen a block. + expect(strut!.forceStrutHeight, isTrue); + expect(strut.fontFamily, widget.style?.fontFamily); + expect(strut.fontSize, widget.style?.fontSize); + } + final outcomes = selectable.firstWhere( + (widget) => (widget.data ?? '').contains('success → build'), + ); + final raw = selectable.firstWhere( + (widget) => (widget.data ?? '').startsWith('{'), + ); + expect(outcomes.strutStyle, raw.strutStyle); + }); + + test('field labels are the web words', () { + expect(stageConfigLabel('budget_usd'), 'Budget (USD)'); + expect(stageConfigLabel('budget_tokens'), 'Budget (tokens)'); + expect(stageConfigLabel('custom'), 'custom'); + }); +} diff --git a/app/tool/stage_definition_probe.dart b/app/tool/stage_definition_probe.dart new file mode 100644 index 00000000..046bf874 --- /dev/null +++ b/app/tool/stage_definition_probe.dart @@ -0,0 +1,148 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart'; +import 'package:pipelines_app/ui/adaptive/host.dart'; + +/// A definition with an authored stage (including an unknown future field), a +/// declared route to a terminal, and no declaration for `ghost`. +JsonMap _graph() => { + 'stages': [ + { + 'key': 'plan', + 'type': 'model', + 'prompt': 'Plan the change.', + 'output': 'A short plan.', + 'edges': {'success': 'build', 'error': '#'}, + 'fallback_error': true, + 'configs': { + 'provider': 'openai', + 'model': 'gpt-5', + 'budget_usd': 12.5, + }, + 'blocks': {'tools': 'shell\nread_file'}, + 'limits': { + 'max_visits': 2, + 'on': ['error'], + }, + 'memory': {'context': 'latest'}, + 'notify': { + 'on': ['failure'], + 'destination': 'ops@example.test', + 'artifacts': ['run.log'], + }, + 'future_field': {'kept': true}, + }, + { + 'key': 'build', + 'type': 'shell', + 'edges': {'success': '#success', 'error': '#failure'}, + }, + ], +}; + +/// Isolated browser fixture for the read-only stage definition pane. +/// +/// `style=cupertino` selects the Cupertino host, `dark=1` its dark theme, +/// `scale=2` a real 2x text scale. Every button opens the exact helper the +/// pipeline graph hook will call; nothing contacts a server or reads a run. +void main() { + final parameters = Uri.base.queryParameters; + runApp( + _ProbeApp( + cupertino: parameters['style'] == 'cupertino', + dark: parameters['dark'] == '1', + scale: double.tryParse(parameters['scale'] ?? '') ?? 1, + ), + ); +} + +class _ProbeApp extends StatelessWidget { + const _ProbeApp({ + required this.cupertino, + required this.dark, + required this.scale, + }); + + final bool cupertino; + final bool dark; + final double scale; + + @override + Widget build(BuildContext context) { + Widget scaled(BuildContext context, Widget? child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: child ?? const SizedBox.shrink(), + ); + if (cupertino) { + return CupertinoApp( + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + builder: scaled, + home: const CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar( + middle: Text('Stage definition fixture'), + ), + child: SafeArea(child: _Launcher()), + ), + ); + } + return MaterialApp( + theme: ThemeData( + platform: TargetPlatform.android, + brightness: Brightness.light, + ), + darkTheme: ThemeData( + platform: TargetPlatform.android, + brightness: Brightness.dark, + ), + themeMode: dark ? ThemeMode.dark : ThemeMode.light, + builder: scaled, + home: Scaffold( + appBar: AppBar(title: const Text('Stage definition fixture')), + body: const SafeArea(child: _Launcher()), + ), + ); + } +} + +class _Launcher extends StatelessWidget { + const _Launcher(); + + void _open(BuildContext context, String key) => openStageDefinition( + context, + graph: _graph(), + stageKey: key, + pipelineId: 41, + pipelineName: 'Demo pipeline', + version: 7, + ); + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + return ListView( + padding: const EdgeInsets.all(16), + children: [ + const Text('Fixture home'), + for (final key in ['plan', '#failure', 'ghost']) + Padding( + padding: const EdgeInsets.only(top: 8), + child: cupertino + ? CupertinoButton.filled( + onPressed: () => _open(context, key), + child: Text('$key definition'), + ) + : FilledButton( + onPressed: () => _open(context, key), + child: Text('$key definition'), + ), + ), + ], + ); + } +} diff --git a/app/tool/stage_definition_probe.mjs b/app/tool/stage_definition_probe.mjs new file mode 100644 index 00000000..50377753 --- /dev/null +++ b/app/tool/stage_definition_probe.mjs @@ -0,0 +1,380 @@ +// Browser acceptance for the isolated read-only stage definition pane. +// +// Serves the probe build (`flutter build web -t tool/stage_definition_probe.dart`) +// on an OS-assigned loopback port, drives real headless Chrome, opens the pane +// through the same native helper the manager graph hook uses, asserts the +// pinned identity, actual field values, outcomes, raw unknown fields, terminal +// and unknown-stage states, closes it with Back on both hosts, and writes +// captures. +// +// PROBE_VARIANT=material|cupertino PROBE_SCHEME=dark|light PROBE_SCALE=1|2 \ +// PROBE_WIDTH=1280 PROBE_HEIGHT=900 PROBE_WEB_ROOT= \ +// OPENCODE_ARTIFACT_DIR= node tool/stage_definition_probe.mjs +import { createServer } from 'node:http'; +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 { createHash } from 'node:crypto'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; + +const root = resolve( + process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/stage_definition_probe_web'), +); +const variant = process.env.PROBE_VARIANT ?? 'material'; +const scheme = process.env.PROBE_SCHEME ?? 'dark'; +const scale = process.env.PROBE_SCALE ?? '1'; +const width = Number(process.env.PROBE_WIDTH ?? 1280); +const height = Number(process.env.PROBE_HEIGHT ?? 900); +const chromePath = process.env.CHROME_PATH ?? + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR; +if (!artifactDir) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(artifactDir, { recursive: true }); +const prefix = `stage-definition-${variant}-${scheme}-${scale}x` + + (width === 1280 && height === 900 ? '' : `-${width}x${height}`); +const mime = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.otf': 'font/otf', + '.ttf': 'font/ttf', +}; +const server = createServer(async (req, res) => { + try { + const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').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' }).end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; +const profile = await mkdtemp(join(tmpdir(), 'stage-definition-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) => { + for (let i = 0; i < 140; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +let ws; +try { + const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.method === 'Runtime.exceptionThrown') { + console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails?.exception?.description)); + } + 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' }); + 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); + await send('Emulation.setEmulatedMedia', { + features: [{ name: 'prefers-color-scheme', value: scheme }], + }, session); + await send('Emulation.setDeviceMetricsOverride', { + width, height, deviceScaleFactor: 1, mobile: false, + }, session); + const query = `?style=${variant}&dark=${scheme === 'dark' ? 1 : 0}&scale=${scale}`; + const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/${query}` }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + 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)}`); + return response.result?.result?.value; + }; + await delay(3500); + const loaded = await evaluate('({url:location.href, ready:document.readyState})'); + if (!loaded?.url.includes(`127.0.0.1:${port}/${query}`)) { + throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`); + } + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(2200); + + const labels = () => evaluate( + "[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||(x.innerText||'').trim()).filter(Boolean)", + ); + const bodyText = async () => [await evaluate('document.body.innerText'), ...(await labels())].join('\n'); + const clickExact = async (label) => { + const point = await evaluate(`(() => { + const e = [...document.querySelectorAll('flt-semantics')].find(x => + (x.getAttribute('aria-label')||(x.innerText||'').trim()).trim() === ${JSON.stringify(label)}); + if (!e) return null; + const r = e.getBoundingClientRect(); + return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; + })()`); + if (!point) throw new Error(`Missing control ${label}: ${JSON.stringify(await labels())}`); + await send('Input.dispatchMouseEvent', { + type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1, + }, session); + await send('Input.dispatchMouseEvent', { + type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1, + }, session); + await delay(1000); + }; + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { + format: 'png', captureBeyondViewport: false, + }, session)).result.data; + const buffer = Buffer.from(data, 'base64'); + const file = `${prefix}-${name}.png`; + await writeFile(join(artifactDir, file), buffer); + return { file, sha1: createHash('sha1').update(buffer).digest('hex') }; + }; + const visible = async (needle, exact = false) => evaluate(`(() => { + const found = [...document.querySelectorAll('flt-semantics')].filter(x => { + const label = (x.getAttribute('aria-label')||(x.innerText||'')).trim(); + return ${exact ? `label === ${JSON.stringify(needle)}` : `label.includes(${JSON.stringify(needle)})`}; + }); + if (!found.length) return null; + found.sort((a, b) => { + const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); + return ra.width * ra.height - rb.width * rb.height; + }); + const r = found[0].getBoundingClientRect(); + return { x: r.x, y: r.y, width: r.width, height: r.height, + visible: r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < innerHeight }; + })()`); + // Scroll by the measured delta instead of fixed steps: a fixed gesture can + // stop with a target half-entered (and its neighbours not built), which is + // exactly what made the raw-section check fail on shorter content. + const scrollTo = async (needle, { exact = false, maxTop = null } = {}) => { + for (let attempt = 0; attempt < 24; attempt++) { + const r = await visible(needle, exact); + const fullyVisible = r && r.width > 0 && r.height > 0 && + r.y >= 32 && r.y + r.height <= height - 32; + if (fullyVisible && (maxTop == null || r.y <= maxTop)) return r; + // Scroll down until the target is fully in view; for a target that must + // sit high (the raw title above its JSON), keep scrolling until it does. + const wanted = r + ? Math.round(r.y - (maxTop ?? height / 2)) + : Math.round(height / 3); + const distance = Math.sign(wanted || 1) * + Math.max(60, Math.min(400, Math.abs(wanted))); + await send('Input.synthesizeScrollGesture', { + x: Math.round(width / 2), y: Math.round(height / 2), + yDistance: -distance, gestureSourceType: 'mouse', speed: 900, + preventFling: true, + }, session); + await delay(300); + } + throw new Error( + `${needle} never scrolled into view: ${JSON.stringify(await bodyText())}`, + ); + }; + // The raw section is one selectable block whose whole value must be + // inspected. Scroll to the pane's end so the JSON tail (the unknown fields + // the raw section exists for) is really on screen, not just built. + const scrollToRaw = async () => { + let previous = null; + for (let attempt = 0; attempt < 16; attempt++) { + const r = await visible('future_field'); + if (r && previous != null && Math.abs(r.y - previous) < 1) { + if (!r.visible || r.y + r.height > height + 1) { + throw new Error(`The raw JSON did not settle in view: ${JSON.stringify(r)}`); + } + return r; + } + previous = r?.y ?? null; + await send('Input.synthesizeScrollGesture', { + x: Math.round(width / 2), y: Math.round(height / 2), + yDistance: -600, gestureSourceType: 'mouse', speed: 900, + preventFling: true, + }, session); + await delay(300); + } + throw new Error( + `The raw JSON never settled: ${JSON.stringify(await bodyText())}`, + ); + }; + const evidence = { variant, scheme, scale, checks: [], captures: [] }; + const expectText = async (needle, context) => { + const text = await bodyText(); + if (!text.includes(needle)) throw new Error(`${context}: missing ${JSON.stringify(needle)}\n${text}`); + }; + + await expectText('Fixture home', 'fixture home'); + await clickExact('plan definition'); + for (const needle of [ + 'Demo pipeline · v7', + 'Plan the change.', + 'A short plan.', + 'success → build', + 'error → FAILURE (terminal)', + ]) { + await expectText(needle, 'declared stage'); + } + // Two two-line blocks must share the host line rhythm. A fallback font for + // the outcomes arrow must not stretch only that block, so compare the whole + // label+value block: equal line counts mean equal heights. + if (width >= 1000) { + const blockHeight = async (prefixText) => evaluate(`(() => { + const found = [...document.querySelectorAll('flt-semantics')].filter(x => + (x.getAttribute('aria-label')||(x.innerText||'')).trim().startsWith(${JSON.stringify(prefixText)})); + if (!found.length) return null; + found.sort((a, b) => { + const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); + return ra.width * ra.height - rb.width * rb.height; + }); + const r = found[0].getBoundingClientRect(); + return { height: r.height, width: r.width }; + })()`); + const outcomes = await blockHeight('Outcomes'); + const tools = await blockHeight('Tools'); + const ratio = outcomes && tools ? outcomes.height / tools.height : 0; + if (!(ratio >= 0.8 && ratio <= 1.25)) { + throw new Error( + `Outcomes line rhythm differs from Tools: ${JSON.stringify({ outcomes, tools, ratio })}`, + ); + } + evidence.rhythm = { + outcomesHeight: outcomes.height, + toolsHeight: tools.height, + ratio, + }; + evidence.checks.push({ + check: 'the outcomes block keeps the host line rhythm of other two-line blocks', + value: ratio, + }); + } + evidence.checks.push({ + check: 'declared stage shows pinned identity and the web field values', + value: true, + }); + const declaredCapture = await capture('declared'); + evidence.captures.push(declaredCapture); + + // Remaining declared fields, reached by scrolling so the probe also covers + // viewports shorter than the full pane. + for (const needle of [ + 'Provider', 'openai', 'Model', 'gpt-5', 'Budget (USD)', '12.5', + 'Tools', 'shell', 'read_file', 'Max visits', 'Limit on', 'Memory', + 'context: latest', + ]) { + await scrollTo(needle); + await expectText(needle, 'declared stage'); + } + evidence.checks.push({ + check: 'every declared field value is present in the rendered pane', + value: true, + }); + + await scrollTo('Notify destination'); + for (const needle of ['Notify on', 'failure', 'Notify destination', 'ops@example.test', 'Notify artifacts', 'run.log']) { + await expectText(needle, 'notify definition'); + } + + const rawJson = await scrollToRaw(); + evidence.rawJsonRect = rawJson; + evidence.rawSectionSeen = (await bodyText()).includes('Raw stage definition'); + for (const needle of ['future_field', 'kept', 'fallback_error']) { + await expectText(needle, 'raw unknown fields'); + } + evidence.checks.push({ + check: 'unknown stage fields remain in the selectable raw JSON', + value: true, + }); + const rawCapture = await capture('raw'); + if (rawCapture.sha1 === declaredCapture.sha1) { + throw new Error('The raw capture is identical to the unscrolled pane'); + } + evidence.captures.push(rawCapture); + + await clickExact('Back'); + await expectText('Fixture home', 'Back'); + evidence.checks.push({ check: 'Back returned to the graph host', value: true }); + + await clickExact('#failure definition'); + const terminalText = await bodyText(); + if (terminalText.includes('#failure')) { + throw new Error(`The terminal title still exposes the raw key: ${terminalText}`); + } + await expectText('Failure definition', 'terminal title'); + for (const needle of [ + 'Success and Failure are definition targets, not recorded visits.', + 'Incoming routes', + 'plan · error* → FAILURE', + 'build · error → FAILURE', + ]) { + await expectText(needle, 'terminal definition'); + } + evidence.checks.push({ + check: 'the terminal page is titled with its display label, not the protocol key', + value: true, + }); + evidence.checks.push({ + check: 'terminal explains definition routes without claiming a visit', + value: true, + }); + evidence.captures.push(await capture('terminal')); + await clickExact('Back'); + await expectText('Fixture home', 'terminal Back'); + + await clickExact('ghost definition'); + await expectText( + 'This stage is not declared in this pipeline version.', + 'unknown stage', + ); + const unknown = await bodyText(); + if (unknown.includes('Raw stage definition') || unknown.includes('Incoming routes')) { + throw new Error(`Unknown stage invented definition content: ${unknown}`); + } + evidence.checks.push({ + check: 'unknown stage has an explicit missing state with no defaults', + value: true, + }); + evidence.captures.push(await capture('unknown')); + await clickExact('Back'); + await expectText('Fixture home', 'unknown Back'); + evidence.checks.push({ check: 'every open used one native bar and Back', value: true }); + evidence.captures.push(await capture('closed')); + + console.log(JSON.stringify(evidence, null, 2)); +} finally { + if (ws?.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify({ id: 2147483647, method: 'Browser.close' })); + } + await Promise.race([once(chrome, 'exit'), delay(3000)]); + ws?.close(); + if (chrome.exitCode === null) chrome.kill('SIGTERM'); + chrome.stderr.destroy(); + chrome.unref(); + await new Promise((resolveClose) => { + server.close(resolveClose); + server.closeAllConnections(); + }); + await rm(profile, { recursive: true, force: true }); +} From 662ea0299b9226c0b94672d49ff28d4402a4fb58 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:27:39 +0100 Subject: [PATCH 15/17] docs(app): track stage pane landing and attention/run-graph queue --- app/PARITY.md | 6 +++--- app/WORK.md | 5 ++++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/app/PARITY.md b/app/PARITY.md index 2403b355..9c5413b1 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -33,8 +33,8 @@ or scratch servers only, never real operator sessions/runs/workflows. | Cancel run | Preview | exact confirm/server-accepted detail+list fold; production cancellation not tested | | Retry/restart | Source actions/dialogs | actual detail controls, accepted new-run navigation, stale/refusal handling | | Human decisions | Preview waiting card/native prompt/exact accepted reply | attention/action URL entry; no production decision answered during tests | -| Run graph | Source projection/visits; definition canvas landed | executed/unvisited routes, live activity, graph clicks open latest RECORDED visit, no definition by default | -| Timeline/recorded visit pane | Preview text rows only; authored pane77 | visit selection, status/outcome/duration/model/target/verdict, artifacts/session/input/output/definition tabs | +| Run graph | Source projection/visits; definition canvas and stage pane landed | executed/unvisited routes, live activity, graph clicks open latest RECORDED visit, no definition by default | +| Timeline/recorded visit pane | Preview text rows only; authored definition pane landed | visit selection, status/outcome/duration/model/target/verdict, artifacts/session/input/output/definition tabs | | Changes/diffs | Preview via run detail | settled-run aggregate gate, recorded file/diff/close/back verified in the real app; per-visit capture entry and paging remain | | Artifact groups | Source model/list | actual visit/run gallery integration and truthful unavailable capture facts | | Artifact preview | Missing | image-primary in-app viewer, video/doc/text/markdown, paging, focus/back, authenticated fetch errors | @@ -52,7 +52,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Saved schedule list | Source | pipeline entry and route registration, exact timer provenance vocabulary | | Schedule editor | Source draft74+CAS guard; active form78 | save/pause/delete wiring, conflict keeps draft, Schedule this run seed | | Search | Source screen | shell entry, close/focus/selection retention, exact pipeline/version/run/field/visit/artifact target routing | -| Needs you | Missing | derived failed/waiting counts, native list/sheet, open/dismiss/clear snapshot, persisted identities | +| Needs you | Source model82; active sheet84 | runs-list bell/count wiring, open/dismiss/clear persistence, notification transitions | | Notifications | Missing | explicit permission/rationale, secure/unsupported/denied states, transition-only dedupe, background question notices | | Mobile replacement build | Scaffold only | Android build at end; all source portable to iOS, isolated IDs; device/OS behavior clearly separate | diff --git a/app/WORK.md b/app/WORK.md index 940501c6..548bee1d 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -46,7 +46,10 @@ All work under app/. Existing applications remain running and unchanged. | C3-form | Native composer control | run? pending | drafts/send/stop UI atop75 | queued | pending | | Chat screen | Live Chat destination + read-only history | run79 /flutter/chat-live-screen | list/detail routing, paging, live one-thread, reconnect | running | pending | | Templates gallery | run76 /c56b5d45 | manager re-ran38 templates tests, rebuilt fixture;7 probe checks/7 captures incl inspected detail | merged main; ancestry verified | entry/route registration pending | -| Stage definition | Native authored stage pane | run77 /flutter/stage-definition | pinned definition identity, outcomes/tools/raw unknown | running | pending | +| Stage definition | run77 retained/d88213d | review result-validation failure; manager verified retained slice and drove both-host probe (5 captures each) | merged main; ancestry verified | graph hook85 next | +| Attention model | run82 /38f8576c + manager224f8ee |13min;44 tests; manager namespaced dismissals to this client and re-ran tests | merged main; ancestry verified | bell/sheet UI84 next | +| Pipeline graph | Graph tab + stage pane wiring | run85 /flutter/pipeline-graph-wire | pinned definition graph, measured canvas, selection to definition | running | pending | +| Needs you UI | Bell + native sheet | run84 /flutter/attention-ui | snapshot clear/dismiss, both hosts | running | pending | | Schedule form | Native schedule draft editor | run78 /flutter/schedule-form | binds74, no save engine | running | pending | ## Next ready work From df6524c7d9c6fa020b70300b63e4219e472ff21b Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:34:21 +0100 Subject: [PATCH 16/17] feat(app): add recorded artifact gallery to the native run detail --- .../artifacts/ui/artifact_external_open.dart | 14 + .../ui/artifact_external_open_stub.dart | 6 + .../ui/artifact_external_open_web.dart | 20 + .../artifacts/ui/artifact_gallery_action.dart | 104 +++++ .../artifacts/ui/artifact_gallery_page.dart | 194 ++++++++ .../ui/artifact_selection_facts.dart | 71 +++ .../artifacts/ui/artifact_visit_list.dart | 50 +-- .../features/runs/ui/run_detail_actions.dart | 3 + app/notes/A1-wire.md | 150 +++++++ .../ui/artifact_gallery_page_test.dart | 321 +++++++++++++ .../runs/ui/run_artifacts_action_test.dart | 161 +++++++ app/tool/artifact_gallery_probe.dart | 232 ++++++++++ app/tool/artifact_gallery_probe.mjs | 421 ++++++++++++++++++ 13 files changed, 1722 insertions(+), 25 deletions(-) create mode 100644 app/lib/features/artifacts/ui/artifact_external_open.dart create mode 100644 app/lib/features/artifacts/ui/artifact_external_open_stub.dart create mode 100644 app/lib/features/artifacts/ui/artifact_external_open_web.dart create mode 100644 app/lib/features/artifacts/ui/artifact_gallery_action.dart create mode 100644 app/lib/features/artifacts/ui/artifact_gallery_page.dart create mode 100644 app/lib/features/artifacts/ui/artifact_selection_facts.dart create mode 100644 app/notes/A1-wire.md create mode 100644 app/test/features/artifacts/ui/artifact_gallery_page_test.dart create mode 100644 app/test/features/runs/ui/run_artifacts_action_test.dart create mode 100644 app/tool/artifact_gallery_probe.dart create mode 100644 app/tool/artifact_gallery_probe.mjs diff --git a/app/lib/features/artifacts/ui/artifact_external_open.dart b/app/lib/features/artifacts/ui/artifact_external_open.dart new file mode 100644 index 00000000..15ae4180 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_external_open.dart @@ -0,0 +1,14 @@ +import '../domain/artifact_url.dart'; +import 'artifact_external_open_stub.dart' + if (dart.library.js_interop) 'artifact_external_open_web.dart' + as impl; + +/// Opens an already validated artifact url with the host's external handler. +/// +/// The url must come from [resolveArtifactUrl]; this capability never resolves, +/// rewrites, fetches or previews it. Returns whether the host accepted the +/// request, so a refusal is reported instead of being silently swallowed. +typedef ArtifactExternalOpen = Future Function(Uri uri); + +Future openArtifactExternally(Uri uri) => + impl.openArtifactExternally(uri); diff --git a/app/lib/features/artifacts/ui/artifact_external_open_stub.dart b/app/lib/features/artifacts/ui/artifact_external_open_stub.dart new file mode 100644 index 00000000..95708cb5 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_external_open_stub.dart @@ -0,0 +1,6 @@ +/// Non-web fallback for external artifact urls. +/// +/// A native launcher needs a platform plugin that this slice does not depend +/// on, so a non-web host reports the refusal instead of pretending to open the +/// link. The page surfaces that message to the operator. +Future openArtifactExternally(Uri uri) async => false; diff --git a/app/lib/features/artifacts/ui/artifact_external_open_web.dart b/app/lib/features/artifacts/ui/artifact_external_open_web.dart new file mode 100644 index 00000000..f57fc411 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_external_open_web.dart @@ -0,0 +1,20 @@ +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +/// Web external open: a new browser tab. The url is already validated by +/// [resolveArtifactUrl]; it is passed through unchanged and never fetched. +/// +/// `window.open` is reached through `js_interop` rather than `dart:html`, so the +/// same source compiles for both the JavaScript and WebAssembly web targets. +Future openArtifactExternally(Uri uri) async { + try { + final opened = globalContext.callMethod( + 'open'.toJS, + uri.toString().toJS, + '_blank'.toJS, + ); + return opened.isDefinedAndNotNull; + } catch (_) { + return false; + } +} diff --git a/app/lib/features/artifacts/ui/artifact_gallery_action.dart b/app/lib/features/artifacts/ui/artifact_gallery_action.dart new file mode 100644 index 00000000..7cffb7c8 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_gallery_action.dart @@ -0,0 +1,104 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../core/transport/pipelines_client.dart'; +import '../../../ui/adaptive/host.dart'; +import 'artifact_external_open.dart'; +import 'artifact_gallery_page.dart'; + +/// The run detail's action label key, so a host can find the one action. +const ValueKey runArtifactsButtonKey = ValueKey( + 'run-detail-artifacts', +); + +const Set _executingStatuses = {'queued', 'running', 'waiting'}; + +/// The detail's `steps` exactly as returned by the server. The pushed page +/// snapshots the returned list once, so it never re-derives on each rebuild. +List runDetailArtifactSteps(JsonMap run) { + final steps = run['steps']; + if (steps is List) return steps; + if (steps is List) return steps.cast(); + return const []; +} + +/// Whether the run detail offers the gallery action at all: only once the +/// loaded detail actually carries steps. A run with no steps has nothing to +/// list, so the action is absent rather than opening a page that says so. +bool showRunArtifactsAction(JsonMap run) => + runDetailArtifactSteps(run).isNotEmpty; + +/// Whether the run is still executing, so the page can say capture pending +/// instead of claiming nothing was recorded. +bool _runExecuting(JsonMap run) => + run['executing'] == true || + _executingStatuses.contains('${run['status'] ?? ''}'.trim().toLowerCase()); + +/// The configured endpoint from the app's shared transport, when the gateway +/// exposes it. Feature fixtures without an endpoint leave it blank, which only +/// disables relative url resolution: an absolute recorded http(s) url still +/// resolves. The url rules themselves live in `artifact_url.dart`. +String _gatewayEndpoint(ApiGateway gateway) { + final endpoint = gateway is PipelinesClient ? gateway.endpoint : null; + return endpoint?.toString() ?? ''; +} + +/// The run detail's standard native action that opens the recorded artifact +/// groups. It is composed only when [showRunArtifactsAction] is true. +class RunArtifactsButton extends StatelessWidget { + const RunArtifactsButton({ + super.key, + required this.run, + required this.gateway, + }); + + final JsonMap run; + final ApiGateway gateway; + + @override + Widget build(BuildContext context) { + final steps = runDetailArtifactSteps(run); + void open() => showArtifactGallery( + context, + steps: steps, + executing: _runExecuting(run), + configuredEndpoint: _gatewayEndpoint(gateway), + ); + if (usesCupertinoHost(context)) { + return CupertinoButton.tinted( + key: runArtifactsButtonKey, + onPressed: open, + child: const Text(artifactGalleryTitle), + ); + } + return FilledButton.tonalIcon( + key: runArtifactsButtonKey, + onPressed: open, + icon: const Icon(Icons.inventory_2_outlined), + label: const Text(artifactGalleryTitle), + ); + } +} + +/// Opens the recorded artifact groups on a native page. The steps are +/// snapshotted once; the page never re-fetches or re-derives them. +Future showArtifactGallery( + BuildContext context, { + required List steps, + bool executing = false, + String configuredEndpoint = '', + ArtifactExternalOpen openExternal = openArtifactExternally, +}) { + final page = ArtifactGalleryPage( + steps: List.unmodifiable(steps), + executing: executing, + configuredEndpoint: configuredEndpoint, + openExternal: openExternal, + ); + return Navigator.of(context).push( + usesCupertinoHost(context) + ? CupertinoPageRoute(builder: (_) => page) + : MaterialPageRoute(builder: (_) => page), + ); +} diff --git a/app/lib/features/artifacts/ui/artifact_gallery_page.dart b/app/lib/features/artifacts/ui/artifact_gallery_page.dart new file mode 100644 index 00000000..9cc12338 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_gallery_page.dart @@ -0,0 +1,194 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../domain/artifact_groups.dart'; +import '../domain/artifact_record.dart'; +import '../domain/artifact_summary.dart'; +import '../domain/artifact_url.dart'; +import 'artifact_external_open.dart'; +import 'artifact_selection_facts.dart'; +import 'artifact_visit_list.dart'; + +/// The gallery page title. +const String artifactGalleryTitle = 'Artifacts'; + +/// A read-only page of recorded stage/visit artifact groups. +/// +/// Selection uses [artifactVisitIdentity], so the same filename in two visits +/// stays two distinct selections. Selecting a row opens a native dialog with +/// the recorded name, MIME and size, the visit's capture facts and, only when +/// the recorded url resolves through [resolveArtifactUrl], native `Open` and +/// `Copy link` actions. It never previews, downloads, shares or filters. +class ArtifactGalleryPage extends StatefulWidget { + const ArtifactGalleryPage({ + super.key, + required this.steps, + this.executing = false, + this.configuredEndpoint = '', + this.openExternal = openArtifactExternally, + }); + + final List steps; + final bool executing; + final String configuredEndpoint; + final ArtifactExternalOpen openExternal; + + @override + State createState() => _ArtifactGalleryPageState(); +} + +class _ArtifactGalleryPageState extends State { + late final Map _stepsByGroup = recordedStepsByGroup( + widget.steps, + ); + String? _selectedIdentity; + String? _status; + + void _select(ArtifactGroup group, ArtifactRecord artifact) { + setState(() { + _selectedIdentity = artifactVisitIdentity(group, artifact); + _status = null; + }); + _showSelected(group, artifact); + } + + Future _showSelected(ArtifactGroup group, ArtifactRecord artifact) { + final step = _stepsByGroup[artifactGroupKey(group.stageKey, group.visit)]; + final resolved = artifact.hasUrl + ? resolveArtifactUrl(widget.configuredEndpoint, artifact.url) + : null; + final facts = ArtifactSelectionFacts( + group: group, + artifact: artifact, + step: step, + resolved: resolved, + ); + if (usesCupertinoHost(context)) { + return showCupertinoDialog( + context: context, + builder: (dialogContext) => CupertinoAlertDialog( + title: Text(artifactDisplayName(artifact)), + content: facts, + actions: [ + if (resolved != null) + CupertinoDialogAction( + isDefaultAction: true, + onPressed: () => _open(resolved, dialogContext), + child: const Text('Open'), + ), + if (resolved != null) + CupertinoDialogAction( + onPressed: () => _copyLink(resolved, dialogContext), + child: const Text('Copy link'), + ), + CupertinoDialogAction( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Close'), + ), + ], + ), + ); + } + return showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(artifactDisplayName(artifact)), + content: SingleChildScrollView(child: facts), + actions: [ + if (resolved != null) + TextButton( + onPressed: () => _copyLink(resolved, dialogContext), + child: const Text('Copy link'), + ), + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Close'), + ), + if (resolved != null) + TextButton( + onPressed: () => _open(resolved, dialogContext), + child: const Text('Open'), + ), + ], + ), + ); + } + + Future _open( + ResolvedArtifactUrl resolved, + BuildContext dialogContext, + ) async { + Navigator.of(dialogContext).pop(); + final opened = await widget.openExternal(resolved.uri); + if (!mounted) return; + setState( + () => _status = opened + ? 'Link opened externally.' + : 'Could not open the link.', + ); + } + + Future _copyLink( + ResolvedArtifactUrl resolved, + BuildContext dialogContext, + ) async { + Navigator.of(dialogContext).pop(); + String message; + try { + await Clipboard.setData(ClipboardData(text: resolved.url)); + message = 'Link copied.'; + } catch (_) { + message = 'Could not copy link.'; + } + if (!mounted) return; + setState(() => _status = message); + } + + @override + Widget build(BuildContext context) { + final groups = artifactGroups(widget.steps); + final summary = widget.steps.isEmpty + ? 'No steps recorded for this run.' + : artifactsHeader(widget.steps, executing: widget.executing); + final body = Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4), + child: Text(summary), + ), + if (_status != null) + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4), + child: Semantics(liveRegion: true, child: Text(_status!)), + ), + if (groups.isNotEmpty) + Expanded( + child: ArtifactVisitList( + groups: groups, + selectedIdentity: _selectedIdentity, + onSelected: _select, + ), + ), + ], + ); + if (usesCupertinoHost(context)) { + return CupertinoPageScaffold( + // Sections paint the grouped background; the page must match it or a + // white seam shows below the last section in light mode. + backgroundColor: CupertinoColors.systemGroupedBackground, + navigationBar: const CupertinoNavigationBar( + middle: Text(artifactGalleryTitle), + ), + child: SafeArea(child: body), + ); + } + return Scaffold( + appBar: AppBar(title: const Text(artifactGalleryTitle)), + body: SafeArea(top: false, child: body), + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_selection_facts.dart b/app/lib/features/artifacts/ui/artifact_selection_facts.dart new file mode 100644 index 00000000..083a322e --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_selection_facts.dart @@ -0,0 +1,71 @@ +import 'package:flutter/widgets.dart'; + +import '../../../core/api_gateway.dart'; +import '../../graph/domain/stage_visits.dart'; +import '../domain/artifact_groups.dart'; +import '../domain/artifact_record.dart'; +import '../domain/artifact_summary.dart'; +import '../domain/artifact_url.dart'; +import 'artifact_visit_list.dart'; + +/// The key one recorded group maps to, used only to find its step. +String artifactGroupKey(String stageKey, int visit) => '$stageKey\u0000$visit'; + +/// Each recorded group's step, keyed by stage and display visit, so a selected +/// row can show its own visit's capture facts. Derives the same grouping the +/// gallery uses; an absent key yields null rather than a fabricated capture. +Map recordedStepsByGroup(List steps) { + final result = {}; + for (final entry in visitsByStage(steps).entries) { + for (var index = 0; index < entry.value.length; index += 1) { + final step = entry.value[index]; + result[artifactGroupKey(entry.key, displayVisit(step, index))] = step; + } + } + return result; +} + +/// The recorded facts of one selected artifact: name, MIME/size, its visit's +/// capture summary and notes, and the url state. Nothing is inferred. +class ArtifactSelectionFacts extends StatelessWidget { + const ArtifactSelectionFacts({ + super.key, + required this.group, + required this.artifact, + required this.step, + required this.resolved, + }); + + final ArtifactGroup group; + final ArtifactRecord artifact; + final JsonMap? step; + final ResolvedArtifactUrl? resolved; + + @override + Widget build(BuildContext context) { + final recordedStep = step; + final url = resolved; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(artifactFactsLabel(artifact)), + const SizedBox(height: 8), + Text(artifactGroupLabel(group)), + if (recordedStep != null) ...[ + const SizedBox(height: 8), + Text(artifactsSummary(recordedStep, count: group.artifacts.length)), + for (final note in artifactCaptureNotes(recordedStep)) + Padding(padding: const EdgeInsets.only(top: 4), child: Text(note)), + ], + if (!artifact.hasUrl) ...[ + const SizedBox(height: 8), + const Text('No artifact URL recorded.'), + ] else if (url == null) ...[ + const SizedBox(height: 8), + const Text('The recorded artifact URL cannot be opened safely.'), + ], + ], + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_visit_list.dart b/app/lib/features/artifacts/ui/artifact_visit_list.dart index 82cf0aa8..043e43a6 100644 --- a/app/lib/features/artifacts/ui/artifact_visit_list.dart +++ b/app/lib/features/artifacts/ui/artifact_visit_list.dart @@ -22,6 +22,25 @@ String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) { return '${group.stageKey}\u0000${group.visit}\u0000$recorded'; } +/// The recorded group heading, matching the web client's group vocabulary. +String artifactGroupLabel(ArtifactGroup group) => + '${group.stageKey} · visit ${group.visit}'; + +/// The displayed artifact name: a missing server name stays explicit. +String artifactDisplayName(ArtifactRecord artifact) => + artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name; + +/// The recorded MIME and byte size, never inferred from the name. +/// +/// The value and its unit are joined by a non-breaking space so a narrow row +/// never wraps `120.6` away from `KiB`. +String artifactFactsLabel(ArtifactRecord artifact) { + final type = artifact.contentType.split(';').first.trim(); + final mime = type.isEmpty ? 'type not recorded' : type; + final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0'); + return '$mime · $size'; +} + /// A read-only, selectable list of recorded artifact groups. /// /// Each group shows its recorded stage and visit, and each row its recorded @@ -60,7 +79,7 @@ class ArtifactVisitList extends StatelessWidget { header: Semantics( container: true, header: true, - child: Text(_groupLabel(group)), + child: Text(artifactGroupLabel(group)), ), hasLeading: false, children: [ @@ -85,7 +104,7 @@ class ArtifactVisitList extends StatelessWidget { child: Semantics( container: true, header: true, - child: Text(_groupLabel(group)), + child: Text(artifactGroupLabel(group)), ), ), for (var index = 0; index < group.artifacts.length; index += 1) @@ -108,25 +127,6 @@ class ArtifactVisitList extends StatelessWidget { ValueKey('${artifactVisitIdentity(group, artifact)}\u0000$index'); } -/// The recorded group heading, matching the web client's group vocabulary. -String _groupLabel(ArtifactGroup group) => - '${group.stageKey} · visit ${group.visit}'; - -/// The displayed artifact name: a missing server name stays explicit. -String _displayName(ArtifactRecord artifact) => - artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name; - -/// The recorded MIME and byte size, never inferred from the name. -/// -/// The value and its unit are joined by a non-breaking space so a narrow row -/// never wraps `120.6` away from `KiB`. -String _facts(ArtifactRecord artifact) { - final type = artifact.contentType.split(';').first.trim(); - final mime = type.isEmpty ? 'type not recorded' : type; - final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0'); - return '$mime · $size'; -} - class _MaterialRow extends StatelessWidget { const _MaterialRow({ super.key, @@ -145,8 +145,8 @@ class _MaterialRow extends StatelessWidget { Widget build(BuildContext context) { return ListTile( selected: selected, - title: Text(_displayName(artifact)), - subtitle: Text(_facts(artifact)), + title: Text(artifactDisplayName(artifact)), + subtitle: Text(artifactFactsLabel(artifact)), trailing: selected ? const Icon(Icons.check) : null, onTap: onSelected == null ? null : () => onSelected!(group, artifact), ); @@ -181,8 +181,8 @@ class _CupertinoRow extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(_displayName(artifact)), - Text(_facts(artifact), style: factsStyle), + Text(artifactDisplayName(artifact)), + Text(artifactFactsLabel(artifact), style: factsStyle), ], ), ), diff --git a/app/lib/features/runs/ui/run_detail_actions.dart b/app/lib/features/runs/ui/run_detail_actions.dart index 699f734c..8639e899 100644 --- a/app/lib/features/runs/ui/run_detail_actions.dart +++ b/app/lib/features/runs/ui/run_detail_actions.dart @@ -1,6 +1,7 @@ import 'package:flutter/widgets.dart'; import '../../../core/api_gateway.dart'; +import '../../artifacts/ui/artifact_gallery_action.dart'; import '../actions/cancel_run_action.dart'; import '../actions/title_action.dart'; import 'run_decision_notice.dart'; @@ -36,6 +37,8 @@ class RunDetailActions extends StatelessWidget { gateway: gateway, onRunChanged: onRunChanged, ), + if (showRunArtifactsAction(run)) + RunArtifactsButton(run: run, gateway: gateway), ], ), RunDecisionNotice(run: run, gateway: gateway, onRunChanged: onRunChanged), diff --git a/app/notes/A1-wire.md b/app/notes/A1-wire.md new file mode 100644 index 00000000..94949244 --- /dev/null +++ b/app/notes/A1-wire.md @@ -0,0 +1,150 @@ +# A1-wire — native Artifacts action and recorded-group gallery + +## What changed + +The run detail now offers a standard native **Artifacts** action whenever the +loaded detail carries steps. It pushes a native page that lists the recorded +stage/visit groups from the landed `artifactGroups`/`ArtifactVisitList`. +Selecting a row opens the host's native dialog with the recorded name, MIME and +size, the visit's own capture facts, and — only when the recorded url resolves +through the existing `resolveArtifactUrl` rules — native **Open** and a separate +**Copy link**. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/artifacts/ui/artifact_gallery_action.dart` | 104 | Action gate, steps snapshot, native button, page push | +| `lib/features/artifacts/ui/artifact_gallery_page.dart` | 194 | The page: summary/empty state, list, selection, Open/Copy link | +| `lib/features/artifacts/ui/artifact_selection_facts.dart` | 71 | Group→step map and the recorded-facts widget | +| `lib/features/artifacts/ui/artifact_external_open.dart` | 14 | `ArtifactExternalOpen` capability + default | +| `lib/features/artifacts/ui/artifact_external_open_web.dart` | 20 | `window.open` through `js_interop` (JS and wasm) | +| `lib/features/artifacts/ui/artifact_external_open_stub.dart` | 6 | Non-web refusal (no launcher dependency in this slice) | +| `lib/features/artifacts/ui/artifact_visit_list.dart` | +28/-25 | Exposes the landed label helpers the page reuses | +| `lib/features/runs/ui/run_detail_actions.dart` | +3 | Composes the action beside Rename/Cancel | +| `test/features/artifacts/ui/artifact_gallery_page_test.dart` | 321 | Page, identity, capture facts, url rules, copy | +| `test/features/runs/ui/run_artifacts_action_test.dart` | 161 | Action gate and wiring on both hosts | +| `tool/artifact_gallery_probe.dart` | 232 | Isolated fixture entry (real `RunDetailView`) | +| `tool/artifact_gallery_probe.mjs` | 421 | Loopback server + headless Chrome driver | + +No shell/main, pubspec, `web/`, Go server, `android/` or other feature was +edited. No dependency was added. + +## Behaviour + +- **Gate.** `showRunArtifactsAction` is true exactly when the loaded detail has + at least one step. A detail with no steps shows no action; the page also has + an explicit `No steps recorded for this run.` state if ever reached. +- **Truthful empty/unavailable.** The page header is the landed + `artifactsHeader`: `Artifacts · N recorded` (`· partial capture` when a visit + excluded/omitted files), `Artifacts · capture pending` while executing, + `No artifacts recorded for this run.` only for a recorded empty capture, and + `Artifacts · capture unavailable` when the field was absent. An unavailable + capture never says nothing was recorded. +- **Selection identity.** `ArtifactVisitList` selection uses + `artifactVisitIdentity`; two visits that both recorded `result.csv` stay two + distinct rows and selections (unit + browser evidence). +- **Facts.** The dialog shows the recorded filename (or `(unnamed artifact)`), + the recorded MIME/size (`type not recorded` when empty), the group's + `stage · visit N`, the visit's `artifactsSummary` and its + `artifactCaptureNotes`. Nothing is inferred from a name. +- **Url rules.** Open/Copy link appear only when `resolveArtifactUrl` returns a + value: absolute http(s) or a server-relative path resolved against the + configured endpoint. Protocol-relative, credentialed, malformed and + non-http(s) urls are rejected and the dialog says + `The recorded artifact URL cannot be opened safely.` A record with no url says + `No artifact URL recorded.` and offers no action. The endpoint comes from the + app's shared `PipelinesClient` when the gateway exposes it; a fixture gateway + leaves it blank, which only disables relative resolution. +- **Open vs copy.** Open calls the injected `ArtifactExternalOpen` with the + resolved `Uri` (web: a new tab via `window.open` reached through + `js_interop`, so it compiles for JS and wasm). Copy link is a separate action + that writes the resolved url to the clipboard. Each reports + `Link opened externally.` / `Could not open the link.` and `Link copied.` / + `Could not copy link.` as an inline live region. +- **Controls.** Material uses `FilledButton.tonalIcon` + `AlertDialog`; Cupertino + uses `CupertinoButton.tinted` + `CupertinoAlertDialog` and the grouped page + background. No fixed row/button sizes, custom font or palette. The Cupertino + action is text-only: the icon variant overflowed by 11 px at 2x text on 390 px + (caught by the existing `run_detail_widget_test`), and dropping the icon keeps + the label whole without clipping. +- **Out of scope, labelled next:** in-app preview/viewer, download, share files, + gallery filters and any network artifact fetch were not written. + +## Checks actually run + +``` +flutter analyze # No issues found +dart format --output=none --set-exit-if-changed ... # 0 changed +flutter test test/features/artifacts test/features/runs # 203 passed +flutter test # 712 passed (whole app) +flutter build web # ✓ Built build/web +flutter build web -t tool/artifact_gallery_probe.dart # ✓ Built build/probe-gallery +node --check tool/artifact_gallery_probe.mjs # ok +node tool/artifact_gallery_probe.mjs ... # 13/13 checks, 16 captures +``` + +`git status --short --untracked-files=all` lists only the files above; +`pubspec.yaml`/`pubspec.lock` are unchanged. No commit, push or deploy. + +## Real browser evidence + +`tool/artifact_gallery_probe.dart` renders the real `RunDetailView` over a fake +`get_run` gateway; `tool/artifact_gallery_probe.mjs` serves the build on an +OS-assigned loopback port and drives headless Chrome. Recorded urls point at the +probe's own loopback origin (plus unsafe/no-url/empty/unavailable states). No +server or operator run was touched. + +13/13 checks passed; 16 captures in +`/Users/alan/.local/share/pipelines/data/artifacts/81/public/a1-wire/` +(`evidence.json` holds the machine-readable result): + +- The run detail offers the native Artifacts action; the page lists the actual + recorded rows (`build.log`, `shot.png`, two `result.csv` visits, group + headings, MIME/size), not nav labels. +- Selecting the lower duplicate `result.csv` selected `reviewer · visit 2` with + its own `Artifacts · 1 recorded · partial capture` and + `2 files excluded from artifact capture.` +- The safe selection offers native **Open** and a separate **Copy link**; a + protocol-relative url offers neither and shows the unsafe wording; a url-less + record shows `No artifact URL recorded.` and no action. +- A recorded empty capture says `No artifacts recorded for this run.`; an + unavailable capture says `Artifacts · capture unavailable` and never the empty + wording. +- Cupertino lists the same rows with its native dialog and actions; dark + Cupertino dialog text samples light (max luminance 1.0). +- Both hosts at 320 px / 2x text keep the recorded rows, facts and actions + whole. + +Captures: `a1w-material-{detail,gallery,selected,open,unsafe,nourl,empty, +unavailable}.png`, `a1w-cupertino-{gallery,selected,dark-gallery, +dark-selected}.png`, `a1w-{material,cupertino}-2x-320-{gallery,selected}.png`. + +## Not verified / limits + +- The actual new-tab open could not be driven in headless Chrome: a synthetic + semantics activation carries no user gesture, so the app reports its honest + `Could not open the link.` refusal path. The browser proves the action is + offered only for a safe resolved url; the widget test proves the exact + `http://127.0.0.1:8081/artifacts/1/1/result.csv` uri handed to the opener and + the clipboard write. A genuine user tap was not captured. +- Non-web external open returns false (no launcher dependency is in scope); the + page reports that refusal. Mobile targets were not built or run, so **mobile + remains unverified**. +- All data is fixture data; no live server or operator run was used. +- Page/viewer/share/download/filters are not part of this slice and are labelled + as next work. + +## Manager completion after the Code deadline + +The Code visit hit its 30-minute deadline while still active; its session settled +and all edits were retained. No retry was started. The manager confirmed the dirty +paths were exactly this slice, then ran the focused artifacts/UI tests (29 pass), +analysis, and the fixture probe. The probe covers both hosts plus 320px/2x and +produced 16 captures (detail, gallery, selected facts, Open, unsafe url, no url, +empty, unavailable capture). The Cupertino dark selected dialog and the Material +320px/2x selected dialog were inspected: recorded name/MIME/size, the visit's own +capture facts, excluded-file note, and distinct Open / Copy link / Close where a +safe url exists. + +Deliberate scope: this slice links to a validated url externally and copies that +link. It performs no in-app preview, download or file sharing, so the artifact +viewer/Share rows in app/PARITY.md remain open. diff --git a/app/test/features/artifacts/ui/artifact_gallery_page_test.dart b/app/test/features/artifacts/ui/artifact_gallery_page_test.dart new file mode 100644 index 00000000..c1a4fe72 --- /dev/null +++ b/app/test/features/artifacts/ui/artifact_gallery_page_test.dart @@ -0,0 +1,321 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; + +import '../domain/artifact_fixtures.dart'; + +enum _Platform { material, cupertino } + +JsonMap _recorded( + String name, { + String url = '', + String contentType = 'text/csv', + int sizeBytes = 2048, +}) => artifact( + name, + url: url.isEmpty ? null : url, + contentType: contentType, + sizeBytes: sizeBytes, +); + +/// Two visits of `review` record the same filename; the second visit also +/// records `notes.md`. `build` records one file. +List _steps() => [ + step( + stage: 'build', + sequence: 1, + visit: 1, + artifacts: [_recorded('build.log', contentType: 'text/plain')], + ), + step( + stage: 'review', + sequence: 2, + visit: 1, + artifacts: [ + _recorded('result.csv'), + _recorded('notes.md', contentType: 'text/markdown'), + ], + ), + step( + stage: 'review', + sequence: 3, + visit: 2, + artifacts: [_recorded('result.csv', url: '/artifacts/1/2/result.csv')], + ), +]; + +Future _pumpGallery( + WidgetTester tester, + _Platform platform, + List steps, { + String configuredEndpoint = '', + bool executing = false, + Future Function(Uri)? openExternal, +}) async { + final page = ArtifactGalleryPage( + steps: steps, + executing: executing, + configuredEndpoint: configuredEndpoint, + openExternal: openExternal ?? (_) async => true, + ); + await tester.pumpWidget( + platform == _Platform.material + ? MaterialApp(home: page) + : CupertinoApp(home: page), + ); + await tester.pumpAndSettle(); +} + +Finder _inDialog(_Platform platform, String text) => find.descendant( + of: find.byType( + platform == _Platform.material ? AlertDialog : CupertinoAlertDialog, + ), + matching: find.text(text), +); + +void main() { + for (final platform in _Platform.values) { + testWidgets('${platform.name}: lists recorded groups and rows', ( + tester, + ) async { + await _pumpGallery(tester, platform, _steps()); + expect(find.text('Artifacts · 4 recorded'), findsOneWidget); + expect(find.text('build · visit 1'), findsOneWidget); + expect(find.text('review · visit 1'), findsOneWidget); + expect(find.text('review · visit 2'), findsOneWidget); + expect(find.text('result.csv'), findsNWidgets(2)); + expect(find.text('notes.md'), findsOneWidget); + expect(find.text('text/markdown · 2.0\u00a0KiB'), findsOneWidget); + }); + + testWidgets('${platform.name}: duplicate filename stays visit distinct', ( + tester, + ) async { + final steps = _steps(); + await _pumpGallery(tester, platform, steps); + await tester.tap(find.text('result.csv').at(1)); + await tester.pumpAndSettle(); + + final groups = artifactGroups(steps); + final visitTwo = groups.firstWhere( + (group) => group.stageKey == 'review' && group.visit == 2, + ); + final list = tester.widget( + find.byType(ArtifactVisitList), + ); + expect( + list.selectedIdentity, + artifactVisitIdentity(visitTwo, visitTwo.artifacts.single), + ); + expect(_inDialog(platform, 'review · visit 2'), findsOneWidget); + expect(_inDialog(platform, 'review · visit 1'), findsNothing); + expect(_inDialog(platform, 'Artifacts · 1 recorded'), findsOneWidget); + }); + } + + testWidgets('capture notes and partial label come from the visit step', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step( + stage: 'review', + visit: 1, + artifacts: [_recorded('result.csv'), _recorded('notes.md')], + skipped: 2, + truncated: 3, + ), + ]); + expect( + find.text('Artifacts · 2 recorded · partial capture'), + findsOneWidget, + ); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + expect( + _inDialog(_Platform.material, 'Artifacts · 2 recorded · partial capture'), + findsOneWidget, + ); + expect( + _inDialog(_Platform.material, '2 files excluded from artifact capture.'), + findsOneWidget, + ); + expect( + _inDialog( + _Platform.material, + '3 files omitted by artifact capture limits.', + ), + findsOneWidget, + ); + }); + + testWidgets('an unavailable capture never claims nothing was recorded', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step(stage: 'review', visit: 1, includeArtifacts: false), + ]); + expect(find.text('Artifacts · capture unavailable'), findsOneWidget); + expect(find.text('No artifacts recorded for this run.'), findsNothing); + }); + + testWidgets('a recorded empty capture says nothing was recorded', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step(stage: 'review', visit: 1, artifacts: const []), + ]); + expect(find.text('No artifacts recorded for this run.'), findsOneWidget); + expect(find.byType(ArtifactVisitList), findsNothing); + }); + + testWidgets('a page with no steps says so explicitly', (tester) async { + await _pumpGallery(tester, _Platform.material, const []); + expect(find.text('No steps recorded for this run.'), findsOneWidget); + }); + + testWidgets('Open uses the resolved recorded url only', (tester) async { + final opened = []; + await _pumpGallery( + tester, + _Platform.material, + [ + step( + stage: 'review', + visit: 1, + artifacts: [ + _recorded('result.csv', url: '/artifacts/1/1/result.csv'), + ], + ), + ], + configuredEndpoint: 'ws://127.0.0.1:8081/connect', + openExternal: (uri) async { + opened.add(uri); + return true; + }, + ); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + await tester.tap(_inDialog(_Platform.material, 'Open')); + await tester.pumpAndSettle(); + + expect(opened, [ + Uri.parse('http://127.0.0.1:8081/artifacts/1/1/result.csv'), + ]); + expect(find.text('Link opened externally.'), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + }); + + testWidgets('an unsafe recorded url offers no open or copy action', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step( + stage: 'review', + visit: 1, + artifacts: [_recorded('result.csv', url: '//evil.test/result.csv')], + ), + ], configuredEndpoint: 'ws://127.0.0.1:8081/connect'); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + expect( + _inDialog( + _Platform.material, + 'The recorded artifact URL cannot be opened safely.', + ), + findsOneWidget, + ); + expect(_inDialog(_Platform.material, 'Open'), findsNothing); + expect(_inDialog(_Platform.material, 'Copy link'), findsNothing); + }); + + testWidgets('a record with no url is explicit and offers no action', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step( + stage: 'review', + visit: 1, + artifacts: [ + { + 'name': 'result.csv', + 'url': '', + 'content_type': 'text/csv', + 'size_bytes': 10, + }, + ], + ), + ]); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + expect( + _inDialog(_Platform.material, 'No artifact URL recorded.'), + findsOneWidget, + ); + expect(_inDialog(_Platform.material, 'Open'), findsNothing); + }); + + testWidgets('Copy link copies the resolved url, separate from Open', ( + tester, + ) async { + final copied = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied.add((call.arguments as Map)['text'] as String); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final opened = []; + await _pumpGallery( + tester, + _Platform.material, + [ + step( + stage: 'review', + visit: 1, + artifacts: [ + _recorded('result.csv', url: '/artifacts/1/1/result.csv'), + ], + ), + ], + configuredEndpoint: 'ws://127.0.0.1:8081/connect', + openExternal: (uri) async { + opened.add(uri); + return true; + }, + ); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + await tester.tap(_inDialog(_Platform.material, 'Copy link')); + await tester.pumpAndSettle(); + + expect(copied, ['http://127.0.0.1:8081/artifacts/1/1/result.csv']); + expect(opened, isEmpty); + expect(find.text('Link copied.'), findsOneWidget); + }); + + testWidgets('an executing run says capture pending', (tester) async { + await _pumpGallery(tester, _Platform.material, [ + step( + stage: 'review', + visit: 1, + includeArtifacts: false, + status: 'running', + ), + ], executing: true); + expect(find.text('Artifacts · capture pending'), findsOneWidget); + }); +} diff --git a/app/test/features/runs/ui/run_artifacts_action_test.dart b/app/test/features/runs/ui/run_artifacts_action_test.dart new file mode 100644 index 00000000..1a654187 --- /dev/null +++ b/app/test/features/runs/ui/run_artifacts_action_test.dart @@ -0,0 +1,161 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_action.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +import '../../artifacts/domain/artifact_fixtures.dart'; + +enum _Platform { material, cupertino } + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.detail); + final JsonMap detail; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type != 'get_run') throw UnsupportedError(type); + return Future.value({'run_detail': detail}); + } +} + +JsonMap _run({required List steps}) => { + 'id': 21, + 'title': 'Artifacts wiring run', + 'name': 'gallery', + 'status': 'succeeded', + 'steps': steps, +}; + +Future _pumpDetail( + WidgetTester tester, + _Platform platform, + RunsController controller, + ApiGateway gateway, +) async { + tester.view.physicalSize = const Size(500, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final view = RunDetailView( + controller: controller, + gateway: gateway, + onBack: () {}, + ); + await tester.pumpWidget( + platform == _Platform.material + ? MaterialApp(home: Scaffold(body: view)) + : CupertinoApp( + builder: (context, app) => Theme( + data: ThemeData(platform: TargetPlatform.iOS), + child: app!, + ), + home: CupertinoPageScaffold(child: view), + ), + ); + await tester.pumpAndSettle(); +} + +Future _loaded(ApiGateway gateway) async { + final controller = RunsController(RunsRepository(gateway)); + await controller.select(21); + return controller; +} + +void main() { + for (final platform in _Platform.values) { + testWidgets('${platform.name}: the action opens the recorded groups', ( + tester, + ) async { + final gateway = _FakeGateway( + _run( + steps: [ + step( + stage: 'implementer', + sequence: 1, + artifacts: [ + artifact( + 'build.log', + contentType: 'text/plain', + sizeBytes: 2337, + ), + ], + ), + step( + stage: 'reviewer', + sequence: 2, + artifacts: [ + artifact( + 'shot.png', + contentType: 'image/png', + sizeBytes: 80544, + ), + ], + ), + ], + ), + ); + final controller = await _loaded(gateway); + addTearDown(controller.dispose); + await _pumpDetail(tester, platform, controller, gateway); + + expect(find.byKey(runArtifactsButtonKey), findsOneWidget); + await tester.tap(find.byKey(runArtifactsButtonKey)); + await tester.pumpAndSettle(); + + expect(find.text('Artifacts · 2 recorded'), findsOneWidget); + expect(find.text('build.log'), findsOneWidget); + expect(find.text('shot.png'), findsOneWidget); + expect(find.text('implementer · visit 1'), findsOneWidget); + expect(find.text('reviewer · visit 1'), findsOneWidget); + }); + } + + testWidgets('the action is offered only when the detail has steps', ( + tester, + ) async { + final gateway = _FakeGateway(_run(steps: const [])); + final controller = await _loaded(gateway); + addTearDown(controller.dispose); + await _pumpDetail(tester, _Platform.material, controller, gateway); + expect(find.byKey(runArtifactsButtonKey), findsNothing); + }); + + testWidgets('a recorded empty capture keeps its explicit wording', ( + tester, + ) async { + final gateway = _FakeGateway( + _run( + steps: [step(stage: 'reviewer', visit: 1, artifacts: const [])], + ), + ); + final controller = await _loaded(gateway); + addTearDown(controller.dispose); + await _pumpDetail(tester, _Platform.material, controller, gateway); + + await tester.tap(find.byKey(runArtifactsButtonKey)); + await tester.pumpAndSettle(); + expect(find.text('No artifacts recorded for this run.'), findsOneWidget); + }); + + testWidgets('an unavailable capture is never reported as empty', ( + tester, + ) async { + final gateway = _FakeGateway( + _run(steps: [step(stage: 'reviewer', visit: 1, includeArtifacts: false)]), + ); + final controller = await _loaded(gateway); + addTearDown(controller.dispose); + await _pumpDetail(tester, _Platform.material, controller, gateway); + + await tester.tap(find.byKey(runArtifactsButtonKey)); + await tester.pumpAndSettle(); + expect(find.text('Artifacts · capture unavailable'), findsOneWidget); + expect(find.text('No artifacts recorded for this run.'), findsNothing); + }); +} diff --git a/app/tool/artifact_gallery_probe.dart b/app/tool/artifact_gallery_probe.dart new file mode 100644 index 00000000..fdaad138 --- /dev/null +++ b/app/tool/artifact_gallery_probe.dart @@ -0,0 +1,232 @@ +// Standalone fixture entry for real-browser run-detail Artifacts evidence. +// +// Build and probe (from app/): +// flutter build web --target tool/artifact_gallery_probe.dart --output build/probe-gallery +// node tool/artifact_gallery_probe.mjs --root build/probe-gallery --out DIR +// +// Server-shaped fixtures only: a fake gateway answers the same get_run envelope +// the app consumes. The recorded urls point at the probe's own loopback origin, +// so the external Open action has a real target. No server or operator run is +// touched. +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.detail); + + final JsonMap detail; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type != 'get_run') throw UnsupportedError(type); + return Future.value({'run_detail': detail}); + } +} + +JsonMap _file( + String name, { + required String url, + required String contentType, + required int sizeBytes, +}) => { + 'name': name, + 'url': url, + 'content_type': contentType, + 'size_bytes': sizeBytes, +}; + +/// The recorded steps for one probe state. `default` carries two visits that +/// both record `result.csv` plus a partial capture on the second visit. +List _steps(String origin, String state) { + if (state == 'unavailable') { + return [ + { + 'stage': 'implementer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + }, + ]; + } + if (state == 'empty') { + return [ + { + 'stage': 'implementer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': const [], + }, + ]; + } + if (state == 'unsafe' || state == 'nourl') { + return [ + { + 'stage': 'reviewer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'result.csv', + url: state == 'unsafe' ? '//evil.test/result.csv' : '', + contentType: 'text/csv', + sizeBytes: 2048, + ), + ], + }, + ]; + } + return [ + { + 'stage': 'implementer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'build.log', + url: '$origin/fixture/build.log', + contentType: 'text/plain; charset=utf-8', + sizeBytes: 2337, + ), + ], + }, + { + 'stage': 'reviewer', + 'sequence': 2, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'result.csv', + url: '$origin/fixture/result.csv', + contentType: 'text/csv', + sizeBytes: 2048, + ), + _file( + 'shot.png', + url: '$origin/fixture/shot.png', + contentType: 'image/png', + sizeBytes: 80544, + ), + ], + }, + { + 'stage': 'reviewer', + 'sequence': 3, + 'status': 'completed', + 'control': {'visit': 2}, + 'artifacts': [ + _file( + 'result.csv', + url: '$origin/fixture/result-2.csv', + contentType: 'text/csv', + sizeBytes: 4096, + ), + ], + 'artifacts_skipped': 2, + }, + ]; +} + +JsonMap _run(String origin, String state) => { + 'id': 31, + 'title': 'Artifacts gallery probe', + 'name': 'gallery', + 'status': 'succeeded', + 'steps': _steps(origin, state), +}; + +void main() { + final params = Uri.base.queryParameters; + final cupertino = params['platform'] == 'cupertino'; + final theme = params['theme'] == 'dark' ? Brightness.dark : Brightness.light; + final origin = params['origin'] ?? 'https://artifacts.invalid'; + final state = params['state'] ?? 'default'; + // Browser text scaling is a fixture input like platform and theme. + final textScale = double.tryParse(params['scale'] ?? '') ?? 1; + final body = _ProbeBody(run: _run(origin, state)); + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + runApp( + CupertinoApp( + title: 'Artifacts probe', + theme: CupertinoThemeData(brightness: theme), + builder: (context, app) => Theme( + data: ThemeData(platform: TargetPlatform.iOS), + child: scaled(context, app), + ), + home: body, + ), + ); + } else { + runApp( + MaterialApp( + title: 'Artifacts probe', + theme: ThemeData(brightness: theme, platform: TargetPlatform.android), + builder: scaled, + home: body, + ), + ); + } +} + +class _ProbeBody extends StatefulWidget { + const _ProbeBody({required this.run}); + + final JsonMap run; + + @override + State<_ProbeBody> createState() => _ProbeBodyState(); +} + +class _ProbeBodyState extends State<_ProbeBody> { + late final _FakeGateway _gateway = _FakeGateway(widget.run); + late final RunsController _controller = RunsController( + RunsRepository(_gateway), + ); + + @override + void initState() { + super.initState(); + _controller.select(31); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final detail = RunDetailView( + controller: _controller, + gateway: _gateway, + onBack: () {}, + ); + if (Theme.of(context).platform == TargetPlatform.iOS) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Runs')), + child: SafeArea(child: detail), + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Runs')), + body: detail, + ); + } +} diff --git a/app/tool/artifact_gallery_probe.mjs b/app/tool/artifact_gallery_probe.mjs new file mode 100644 index 00000000..b57ff4a4 --- /dev/null +++ b/app/tool/artifact_gallery_probe.mjs @@ -0,0 +1,421 @@ +// Real-browser evidence for the run-detail Artifacts action and gallery page. +// +// Usage (from app/): +// flutter build web --target tool/artifact_gallery_probe.dart --output build/probe-gallery +// node tool/artifact_gallery_probe.mjs --root build/probe-gallery --out DIR +// +// Serves the built fixture on an OS-assigned loopback port, drives headless +// Chrome, and records the actual recorded rows, the selection dialog, the safe +// external Open, the empty/unavailable states, both native hosts, dark +// Cupertino and the 320/2x states. No server or operator run is touched. +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 { extname, join, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; + +const args = new Map(); +for (let i = 2; i < process.argv.length; i++) { + const value = process.argv[i]; + if (value.startsWith('--')) args.set(value.slice(2), process.argv[++i]); +} +const root = resolve(args.get('root') ?? 'build/probe-gallery'); +const out = resolve(args.get('out') ?? 'build/artifact-gallery-probe'); +const chromePath = + process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +await mkdir(out, { recursive: true }); + +const mime = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.bin': 'application/octet-stream', + '.frag': 'application/octet-stream', +}; + +const server = createServer(async (req, res) => { + const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + if (pathname.startsWith('/fixture/')) { + res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' }); + res.end(`recorded artifact ${pathname}\n`); + return; + } + try { + let filePath = resolve(root, '.' + pathname); + if (filePath !== root && !filePath.startsWith(root + sep)) { + res.writeHead(403).end(); + return; + } + if (pathname === '/' || pathname.endsWith('/')) filePath = join(filePath, 'index.html'); + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).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(), 'a1w-chrome-')); +const chrome = spawn( + chromePath, + ['--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--disable-popup-blocking', '--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, what) => { + for (let i = 0; i < 120; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`); +}; + +const evidence = { origin, captures: [], checks: [] }; +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(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + 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' }); + const session = (await send('Target.attachToTarget', { + targetId: created.result.targetId, + flatten: true, + })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send('Browser.grantPermissions', { + origin, + permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'], + }); + await send('Emulation.setDeviceMetricsOverride', { + width: 390, height: 844, deviceScaleFactor: 1, mobile: true, + }, session); + + 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)}`); + return response.result?.result?.value; + }; + const labels = () => + evaluate( + "[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || (x.innerText || '').trim()).filter(Boolean)", + ); + const bodyText = () => evaluate('document.body.innerText'); + const hasLabel = async (label) => (await labels()).includes(label); + const clickExact = async (label) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(label)}; + const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim(); + const nodes = [...document.querySelectorAll('flt-semantics')]; + const tappable = nodes.filter(x => x.hasAttribute('flt-tappable')); + // The tappable node is the one the engine listens to; a labelled wrapper + // above it would swallow a synthetic click. + const node = tappable.find(x => text(x) === wanted) + || tappable.find(x => text(x).startsWith(wanted)) + || nodes.find(x => text(x) === wanted); + if (!node) return false; + node.click(); + return true; + })()`); + if (!clicked) throw new Error(`No exact semantics label ${JSON.stringify(label)}: ${JSON.stringify(await labels())}`); + await delay(500); + }; + // The lowest matching row is the later visit's duplicate filename. + const clickLowestPrefix = async (prefix) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(prefix)}; + const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim(); + const candidates = [...document.querySelectorAll('flt-semantics')] + .filter(x => text(x).startsWith(wanted)) + .filter(x => x.hasAttribute('flt-tappable')); + if (!candidates.length) return false; + candidates.sort((a, b) => b.getBoundingClientRect().y - a.getBoundingClientRect().y); + candidates[0].click(); + return true; + })()`); + if (!clicked) throw new Error(`No tappable label starting ${JSON.stringify(prefix)}: ${JSON.stringify(await labels())}`); + await delay(600); + }; + const activate = async () => { + await delay(3200); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + const current = await labels(); + if (!current.some((label) => label.includes('Artifacts gallery probe'))) { + throw new Error(`Flutter semantics unavailable: ${JSON.stringify(current)}`); + } + }; + const navigate = async (url) => { + const navigation = await send('Page.navigate', { url }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await activate(); + }; + const capture = async (name, width = 390, height = 844, scale = 1) => { + await send('Emulation.setDeviceMetricsOverride', { + width, height, deviceScaleFactor: scale, mobile: width < 600, + }, session); + await delay(350); + const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data; + const path = join(out, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + evidence.captures.push(path); + }; + const rectOfPrefix = (prefix) => + evaluate(`(() => { + const wanted = ${JSON.stringify(prefix)}; + const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim(); + const node = [...document.querySelectorAll('flt-semantics')].find(x => text(x).startsWith(wanted)); + if (!node) return null; + const r = node.getBoundingClientRect(); + return { x: r.x, y: r.y, width: r.width, height: r.height }; + })()`); + const brightestPixel = async (rect) => { + const shot = await send('Page.captureScreenshot', { + format: 'png', + clip: { ...rect, scale: 2 }, + }, session); + return evaluate(`(async () => { + const img = new Image(); + img.src = 'data:image/png;base64,${shot.result.data}'; + await img.decode(); + const canvas = document.createElement('canvas'); + canvas.width = img.width; + canvas.height = img.height; + const ctx = canvas.getContext('2d'); + ctx.drawImage(img, 0, 0); + const data = ctx.getImageData(0, 0, img.width, img.height).data; + let max = 0; + for (let i = 0; i < data.length; i += 4) { + const lum = (0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2]) / 255; + if (lum > max) max = lum; + } + return { max, width: img.width, height: img.height }; + })()`); + }; + const openGallery = async (query) => { + await navigate(`${origin}/?${query}`); + if (!(await hasLabel('Artifacts'))) { + throw new Error(`Run detail has no Artifacts action: ${JSON.stringify(await labels())}`); + } + await clickExact('Artifacts'); + await delay(600); + }; + + // Material: recorded rows, duplicate filename, visit-2 capture facts and the + // safe external Open. + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}`); + if (!(await hasLabel('Artifacts'))) { + throw new Error(`Material run detail has no Artifacts action: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'the run detail offers the native Artifacts action', value: true }); + await capture('a1w-material-detail'); + + await clickExact('Artifacts'); + const galleryBody = await bodyText(); + for (const recorded of ['build.log', 'shot.png', 'text/csv', 'implementer · visit 1', 'reviewer · visit 2']) { + if (!galleryBody.includes(recorded)) { + throw new Error(`Gallery is missing recorded row ${recorded}: ${JSON.stringify(galleryBody)}`); + } + } + if (!galleryBody.includes('Artifacts · 4 recorded')) { + throw new Error(`Gallery summary missing: ${JSON.stringify(galleryBody)}`); + } + const resultRows = (await labels()).filter((label) => label.startsWith('result.csv')).length; + if (resultRows < 2) { + throw new Error(`Duplicate result.csv rows missing: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'the gallery lists the actual recorded rows, not nav labels', value: true }); + await capture('a1w-material-gallery'); + + await clickLowestPrefix('result.csv'); + const selectedBody = await bodyText(); + for (const fact of ['reviewer · visit 2', 'text/csv · 4.0\u00a0KiB', 'Artifacts · 1 recorded · partial capture', '2 files excluded from artifact capture.']) { + if (!selectedBody.includes(fact)) { + throw new Error(`Selected visit-2 facts missing ${fact}: ${JSON.stringify(selectedBody)}`); + } + } + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`Selection offers no Open/Copy link: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'the duplicate filename selected visit 2 with its own capture facts', value: true }); + await capture('a1w-material-selected'); + + // The selection offers the safe external Open and a separate Copy link. + // Headless Chrome cannot carry a user activation through a synthetic + // semantics click, so the tab itself is proven by the widget test that + // records the exact uri handed to the opener; the browser proves the actions + // appear only for a url that resolves through the safe rules. + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`Selection offers no Open/Copy link: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ + check: 'the selection offers the native Open and separate Copy link for a safe recorded url', + value: true, + }); + await capture('a1w-material-open'); + + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=unsafe`); + await clickExact('Artifacts'); + await clickLowestPrefix('result.csv'); + const unsafeBody = await bodyText(); + if (!unsafeBody.includes('The recorded artifact URL cannot be opened safely.')) { + throw new Error(`Unsafe url wording missing: ${JSON.stringify(unsafeBody)}`); + } + if ((await hasLabel('Open')) || (await hasLabel('Copy link'))) { + throw new Error(`Unsafe url still offered an action: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'a protocol-relative url offers no open or copy action', value: true }); + await capture('a1w-material-unsafe'); + + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=nourl`); + await clickExact('Artifacts'); + await clickLowestPrefix('result.csv'); + const nourlBody = await bodyText(); + if (!nourlBody.includes('No artifact URL recorded.')) { + throw new Error(`No-url wording missing: ${JSON.stringify(nourlBody)}`); + } + if ((await hasLabel('Open')) || (await hasLabel('Copy link'))) { + throw new Error(`A url-less record still offered an action: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'a record with no url is explicit and offers no action', value: true }); + await capture('a1w-material-nourl'); + + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=empty`); + await clickExact('Artifacts'); + const emptyBody = await bodyText(); + if (!emptyBody.includes('No artifacts recorded for this run.')) { + throw new Error(`Recorded empty capture wording missing: ${JSON.stringify(emptyBody)}`); + } + evidence.checks.push({ check: 'a recorded empty capture says nothing was recorded', value: true }); + await capture('a1w-material-empty'); + + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=unavailable`); + await clickExact('Artifacts'); + const unavailableBody = await bodyText(); + if (!unavailableBody.includes('Artifacts · capture unavailable')) { + throw new Error(`Unavailable capture wording missing: ${JSON.stringify(unavailableBody)}`); + } + if (unavailableBody.includes('No artifacts recorded for this run.')) { + throw new Error('Unavailable capture claimed nothing was recorded'); + } + evidence.checks.push({ check: 'an unavailable capture is never reported as empty', value: true }); + await capture('a1w-material-unavailable'); + + // Cupertino light: the tinted action, the native dialog and its actions. + await openGallery(`platform=cupertino&theme=light&origin=${encodeURIComponent(origin)}`); + const cupertinoBody = await bodyText(); + if (!cupertinoBody.includes('shot.png') || !cupertinoBody.includes('reviewer · visit 2')) { + throw new Error(`Cupertino gallery missing recorded rows: ${JSON.stringify(cupertinoBody)}`); + } + evidence.checks.push({ check: 'Cupertino lists the same recorded rows', value: true }); + await capture('a1w-cupertino-gallery'); + await clickLowestPrefix('result.csv'); + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`Cupertino selection offers no actions: ${JSON.stringify(await labels())}`); + } + const cupertinoSelected = await bodyText(); + if (!cupertinoSelected.includes('Artifacts · 1 recorded · partial capture')) { + throw new Error(`Cupertino selection lost its capture facts: ${JSON.stringify(cupertinoSelected)}`); + } + evidence.checks.push({ check: 'Cupertino selection shows the recorded facts and native actions', value: true }); + await capture('a1w-cupertino-selected'); + + // Cupertino dark: the gallery and its dialog on the dark host. + await openGallery(`platform=cupertino&theme=dark&origin=${encodeURIComponent(origin)}`); + await capture('a1w-cupertino-dark-gallery'); + await clickLowestPrefix('result.csv'); + const darkLabels = await labels(); + const darkTitle = darkLabels.find((label) => label.startsWith('result.csv')); + const titleRect = await rectOfPrefix('result.csv'); + const darkText = [await bodyText(), ...darkLabels].join('\n'); + if (!darkText.includes('Artifacts · 1 recorded · partial capture')) { + throw new Error(`Dark Cupertino dialog did not render: ${JSON.stringify(darkText)}`); + } + if (!titleRect) throw new Error(`Dark Cupertino dialog title missing: ${JSON.stringify(darkLabels)}`); + const luminance = await brightestPixel(titleRect); + if (luminance.max < 0.5) { + throw new Error(`Dark Cupertino dialog text is not light: ${JSON.stringify(luminance)}`); + } + evidence.checks.push({ + check: 'dark Cupertino dialog text is light on the popup surface', + value: true, + luminance: luminance.max, + title: darkTitle, + }); + await capture('a1w-cupertino-dark-selected'); + + // 320 px at 2x text on both hosts: the recorded rows and facts stay whole. + const openScaled = async (platform, prefix) => { + await openGallery(`platform=${platform}&theme=light&scale=2&origin=${encodeURIComponent(origin)}`); + const scaled = await bodyText(); + for (const recorded of ['build.log', 'shot.png', 'reviewer · visit 2']) { + if (!scaled.includes(recorded)) { + throw new Error(`2x gallery missing ${recorded}: ${JSON.stringify(scaled)}`); + } + } + await capture(`${prefix}-gallery`, 320, 720, 1); + await clickLowestPrefix('result.csv'); + const facts = await bodyText(); + if (!facts.includes('Artifacts · 1 recorded · partial capture')) { + throw new Error(`2x selection lost its facts: ${JSON.stringify(facts)}`); + } + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`2x selection lost its actions: ${JSON.stringify(await labels())}`); + } + await capture(`${prefix}-selected`, 320, 720, 1); + }; + await openScaled('material', 'a1w-material-2x-320'); + evidence.checks.push({ check: 'Material 2x/320 keeps the recorded rows, facts and actions', value: true }); + await openScaled('cupertino', 'a1w-cupertino-2x-320'); + evidence.checks.push({ check: 'Cupertino 2x/320 keeps the recorded rows, facts and actions', value: true }); + + console.log(JSON.stringify(evidence, 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 }); +} From 4f2f87b445e3a85a3fd2ef34b2af596dbe433fe2 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 22:44:40 +0100 Subject: [PATCH 17/17] test(app): verify the artifact gallery inside the real app run detail --- app/PARITY.md | 4 ++-- app/tool/runs_probe.mjs | 18 ++++++++++++++++++ app/tool/runs_probe_server.mjs | 16 ++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/app/PARITY.md b/app/PARITY.md index 9c5413b1..323155ac 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -36,8 +36,8 @@ or scratch servers only, never real operator sessions/runs/workflows. | Run graph | Source projection/visits; definition canvas and stage pane landed | executed/unvisited routes, live activity, graph clicks open latest RECORDED visit, no definition by default | | Timeline/recorded visit pane | Preview text rows only; authored definition pane landed | visit selection, status/outcome/duration/model/target/verdict, artifacts/session/input/output/definition tabs | | Changes/diffs | Preview via run detail | settled-run aggregate gate, recorded file/diff/close/back verified in the real app; per-visit capture entry and paging remain | -| Artifact groups | Source model/list | actual visit/run gallery integration and truthful unavailable capture facts | -| Artifact preview | Missing | image-primary in-app viewer, video/doc/text/markdown, paging, focus/back, authenticated fetch errors | +| Artifact groups | Preview: run detail → recorded groups, selection facts, external Open/Copy link | present the visit's turn documents (input.md/memory.md/output.md, session.html) as gallery entries; in-app viewer next | +| Artifact preview | Missing | image-primary in-app viewer, video/doc/text/markdown, paging, focus/back, authenticated fetch errors (gallery currently links out only) | | Artifact actions | Source safe URL resolution | separate external-open/copy/download; SHARE REAL NAMED MIME FILES, not links; slow activation/cancel/errors | | Session audit/export repair facts | Missing UI | session.html read-only open, partial/missing/skipped/repair choices without fabricating complete evidence | | Chat session management | Source | normal Chat destination, directory groups/history/search, shared rename/star/close/reopen/create, local hide/undo/seen state | diff --git a/app/tool/runs_probe.mjs b/app/tool/runs_probe.mjs index 4c2f5fcf..4727a42d 100644 --- a/app/tool/runs_probe.mjs +++ b/app/tool/runs_probe.mjs @@ -281,6 +281,24 @@ try { await clickText('Back', { contains: true }); await assertBody('Original prompt'); + // The recorded artifacts action lists each visit's own files, keeps a + // repeated filename distinct, and shows the selected record's facts. + await clickText('Artifacts'); + await assertBody('build · visit 1'); + await assertBody('test · visit 1'); + await assertBody('build-report.html'); + await assertBody('result.csv'); + captures.push(await capture('artifacts-phone-list')); + await delay(500); + await clickText('result.csv', { contains: true }); + await assertBody('text/csv'); + await assertBody('4.0'); + captures.push(await capture('artifacts-phone-selected')); + await clickText('Close'); + await delay(400); + await clickText('Back', { contains: true }); + await assertBody('Original prompt'); + await setSize(1280, 800); await assertBody('Original prompt'); const desktopDetail = await capture('i1-runs-desktop-detail'); diff --git a/app/tool/runs_probe_server.mjs b/app/tool/runs_probe_server.mjs index 2ae957f1..aa7d9d55 100644 --- a/app/tool/runs_probe_server.mjs +++ b/app/tool/runs_probe_server.mjs @@ -130,6 +130,14 @@ function detail(id, live, canceled = false) { omitted: 0, diagnostic: '', }, + artifacts: [ + { + name: 'build-report.html', + size_bytes: 2048, + content_type: 'text/html; charset=utf-8', + url: '/artifacts/1/3/build-report.html', + }, + ], }, { stage: 'test', @@ -137,6 +145,14 @@ function detail(id, live, canceled = false) { status: status === 'failed' ? 'failed' : 'completed', outcome: status === 'failed' ? 'failure' : 'success', target: status === 'failed' ? '#failure' : '#success', + artifacts: [ + { + name: 'result.csv', + size_bytes: 4096, + content_type: 'text/csv', + url: '/artifacts/1/4/result.csv', + }, + ], }, ], };