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 }); +}