diff --git a/app/lib/features/templates/ui/template_create_dialog.dart b/app/lib/features/templates/ui/template_create_dialog.dart new file mode 100644 index 00000000..584b128d --- /dev/null +++ b/app/lib/features/templates/ui/template_create_dialog.dart @@ -0,0 +1,287 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/template_repository.dart'; +import '../domain/template_entry.dart'; +import 'template_create_wording.dart'; + +/// Opens the native create prompt; resolves when it closes. Opening, typing and +/// Cancel send nothing; Create validates the source first and only a passing +/// validate submits it create-only. A refusal keeps the typed name; an accepted +/// `detail` is delivered through [onCreated] once. +Future showTemplateCreateDialog({ + required BuildContext context, + required TemplateEntry template, + required TemplateRepository repository, + required bool cupertino, + required ValueChanged onCreated, +}) { + final dialog = _TemplateCreateDialog( + template: template, + repository: repository, + cupertino: cupertino, + onCreated: onCreated, + ); + return cupertino + ? showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => dialog, + ) + : showDialog( + context: context, + barrierDismissible: false, + builder: (_) => dialog, + ); +} + +class _TemplateCreateDialog extends StatefulWidget { + const _TemplateCreateDialog({ + required this.template, + required this.repository, + required this.cupertino, + required this.onCreated, + }); + + final TemplateEntry template; + final TemplateRepository repository; + final bool cupertino; + final ValueChanged onCreated; + + @override + State<_TemplateCreateDialog> createState() => _TemplateCreateDialogState(); +} + +class _TemplateCreateDialogState extends State<_TemplateCreateDialog> { + final _name = TextEditingController(); + final _feedback = GlobalKey(); + bool _sending = false; + String? _error; + String? _created; + + @override + void initState() { + super.initState(); + _name.addListener(_onNameChanged); + } + + @override + void dispose() { + _name.removeListener(_onNameChanged); + _name.dispose(); + super.dispose(); + } + + void _onNameChanged() { + if (mounted) setState(() {}); + } + + bool get _fieldEnabled => !_sending && _created == null; + bool get _canSubmit => _fieldEnabled && _name.text.trim().isNotEmpty; + + void _cancel() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _create() async { + if (!_canSubmit) return; + final submitted = _name.text; + setState(() { + _sending = true; + _error = null; + }); + JsonMap? detail; + try { + await widget.repository.validate(widget.template.source); + detail = await widget.repository.submit( + submitted, + widget.template.source, + ); + } catch (error) { + if (!mounted) return; + setState(() { + _sending = false; + _error = describeTemplateCreateError(error); + }); + _revealFeedback(); + return; + } + if (!mounted) return; + final created = templateCreatedName(detail, submitted); + setState(() { + _sending = false; + _created = created; + }); + _revealFeedback(); + widget.onCreated(detail); + } + + /// The refusal/success line sits directly under the field, but a tall dialog + /// can still be scrolled away; bring it into view when it appears so a + /// refusal or an accepted create is never a silent no-op. Scrolling only when + /// it does not already fit keeps the title and field in place. + void _revealFeedback() { + WidgetsBinding.instance.addPostFrameCallback((_) { + final feedback = _feedback.currentContext; + if (feedback == null) return; + final box = feedback.findRenderObject(); + final scrollable = Scrollable.maybeOf(feedback); + final viewport = RenderAbstractViewport.maybeOf(box); + if (box is! RenderBox || !box.attached || scrollable == null) return; + if (viewport == null) return; + final position = scrollable.position; + final top = viewport.getOffsetToReveal(box, 0).offset; + final start = position.pixels; + final end = start + position.viewportDimension; + if (top >= start - 1 && top + box.size.height <= end + 1) return; + final target = top < start + ? top + : viewport.getOffsetToReveal(box, 1).offset; + position.jumpTo( + target + .clamp(position.minScrollExtent, position.maxScrollExtent) + .toDouble(), + ); + }); + } + + @override + Widget build(BuildContext context) { + final color = widget.cupertino + ? CupertinoColors.systemRed.resolveFrom(context) + : Theme.of(context).colorScheme.error; + final content = Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _field(), + // Feedback stays next to the field it belongs to. The note below can + // be pushed out of the dialog's scroll viewport on a short, large-text + // screen; a refusal or success line must not be. + Column( + key: _feedback, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + error, + key: templateCreateErrorKey, + style: TextStyle(color: color), + ), + ), + if (_created case final created?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + templateCreateSuccess(created), + key: templateCreateSuccessKey, + ), + ), + ], + ), + const SizedBox(height: 12), + const Text(templateCreateNote), + ], + ); + final actions = [ + _dialogAction( + key: templateCreateCancelKey, + onPressed: _sending ? null : _cancel, + child: Text( + _created == null + ? templateCreateCancelLabel + : templateCreateCloseLabel, + ), + ), + _dialogAction( + key: templateCreateConfirmKey, + primary: true, + onPressed: _canSubmit ? _create : null, + child: Text( + _sending ? templateCreateSendingLabel : templateCreateConfirmLabel, + ), + ), + ]; + final title = Text(templateCreateTitle(widget.template)); + if (!widget.cupertino) { + return PopScope( + canPop: !_sending, + child: AlertDialog( + scrollable: true, + title: title, + content: content, + actions: actions, + ), + ); + } + return PopScope( + canPop: !_sending, + child: CupertinoAlertDialog( + title: title, + content: content, + actions: actions, + ), + ); + } + + Widget _field() { + // A wrapping label above the field, like the browser's label span: the + // Material floating label is ellipsized to `New pipeline name (requ…` at 2x + // text, and a Cupertino placeholder is not exposed as the field's name. + // Merging the visible label into the field gives both hosts one node with + // the exact wording and the field's value. + final field = widget.cupertino + ? CupertinoTextField( + key: templateCreateNameKey, + controller: _name, + enabled: _fieldEnabled, + autofocus: true, + textInputAction: TextInputAction.done, + onSubmitted: (_) => _create(), + ) + : TextField( + key: templateCreateNameKey, + controller: _name, + enabled: _fieldEnabled, + autofocus: true, + textInputAction: TextInputAction.done, + onSubmitted: (_) => _create(), + ); + return MergeSemantics( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text(templateCreateNameLabel), + const SizedBox(height: 8), + field, + ], + ), + ); + } + + Widget _dialogAction({ + required Key key, + required VoidCallback? onPressed, + required Widget child, + bool primary = false, + }) { + if (widget.cupertino) { + return CupertinoDialogAction( + key: key, + isDefaultAction: primary, + onPressed: onPressed, + child: child, + ); + } + if (primary) { + return FilledButton(key: key, onPressed: onPressed, child: child); + } + return TextButton(key: key, onPressed: onPressed, child: child); + } +} diff --git a/app/lib/features/templates/ui/template_create_wording.dart b/app/lib/features/templates/ui/template_create_wording.dart new file mode 100644 index 00000000..c7f889cf --- /dev/null +++ b/app/lib/features/templates/ui/template_create_wording.dart @@ -0,0 +1,42 @@ +import 'package:flutter/widgets.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/template_entry.dart'; + +/// The browser client's create-from-template wording, kept verbatim. +const templateCreateNameLabel = 'New pipeline name (required)'; +const templateCreateNote = + "Creates a new draft pipeline on the server from this template's source; it is not run."; +const templateCreateConfirmLabel = 'Create'; +const templateCreateSendingLabel = 'Creating…'; +const templateCreateCancelLabel = 'Cancel'; +const templateCreateCloseLabel = 'Close'; + +/// Stable test/semantics keys for the prompt. +const templateCreateNameKey = ValueKey('template-create-name'); +const templateCreateConfirmKey = ValueKey('template-create-confirm'); +const templateCreateCancelKey = ValueKey('template-create-cancel'); +const templateCreateErrorKey = ValueKey('template-create-error'); +const templateCreateSuccessKey = ValueKey('template-create-success'); + +/// `Create from {name}`, a blank name falling back to the template key. +String templateCreateTitle(TemplateEntry template) => + 'Create from ${template.name.trim().isNotEmpty ? template.name : template.key}'; + +/// The server's own created name, else the submitted name, trimmed. +String templateCreatedName(JsonMap detail, String submittedName) { + final name = '${detail['name'] ?? ''}'.trim(); + return name.isNotEmpty ? name : submittedName.trim(); +} + +/// `Created "{name}". It is in the Pipelines list.` — the browser's exact line. +String templateCreateSuccess(String created) => + 'Created "$created". It is in the Pipelines list.'; + +/// The server's refusal, verbatim; only a blank reason gets a generic sentence. +String describeTemplateCreateError(Object error) { + final message = '$error'; + return message.trim().isEmpty + ? 'The server did not create the pipeline.' + : message; +} diff --git a/app/notes/T1-create.md b/app/notes/T1-create.md new file mode 100644 index 00000000..80fbf106 --- /dev/null +++ b/app/notes/T1-create.md @@ -0,0 +1,195 @@ +# T1 — native create-from-template prompt + +## Result + +A native Material/Cupertino prompt implements the browser's P5 create flow +without a gallery, route, shell wiring, publish/run control or dependency change. +Create validates the template's source first and only a passing validate submits +it create-only. The accepted detail is reported once through the dialog callback; +nothing is sent while typing, on Cancel, or after a validation refusal. + +This visit addresses the UI review's blocking findings and the earlier +non-blocking notes: + +- **B1 (2x, short phone hid the feedback):** the refusal/success line now sits + directly under the field, before the note, inside the dialog's scroll area, and + the prompt scrolls it into view when it is outside the visible content. At + 2x/360×640 both lines are visible at rest without any scroll. +- **B2 (Cupertino field had no accessible name):** the field now has a visible + `New pipeline name (required)` label merged into the text field's semantics + node (label + value on one node). The Cupertino placeholder was removed + because it duplicated the accessible name; the visible wording is unchanged. +- **S1 (Material label truncated to `New pipeline name (requ…`):** the floating + label was replaced by the same wrapping label above the field that the browser + renders, so the full wording stays visible at 2x. +- **Advisory in-flight lock:** the flow test now asserts the field and Cancel are + disabled and that a system back does not dismiss while a validate is pending. +- The earlier note's file count is corrected below. + +## Files (all new; nothing modified or preserved-changed) + +| File | Lines | Responsibility | +| --- | ---: | --- | +| `lib/features/templates/ui/template_create_dialog.dart` | 287 | Native prompt, labelled field, validate-then-submit state machine, feedback reveal | +| `lib/features/templates/ui/template_create_wording.dart` | 42 | Browser wording verbatim, title/created-name/error helpers, stable keys | +| `test/features/templates/ui/template_create_dialog_test.dart` | 138 | Material blank/Cancel/happy path and validation-refusal coverage | +| `test/features/templates/ui/template_create_flow_test.dart` | 171 | Submit refusal, in-flight lock/double submit, Cupertino branch | +| `test/features/templates/ui/template_create_accessibility_test.dart` | 225 | 2x/3x layout, feedback visibility, both hosts' field semantics | +| `test/features/templates/ui/template_create_test_support.dart` | 127 | Recording gateway, fixture template, Material/Cupertino host | +| `test/features/templates/ui/template_create_wording_test.dart` | 43 | Exact wording and name fallbacks | +| `tool/template_create_probe.dart` | 167 | Isolated in-process fixture entry; Material or Cupertino, optional text scale | +| `tool/template_create_probe.mjs` | 316 | Loopback static server + real headless Chrome driver | +| `notes/T1-create.md` | — | This evidence | + +`TemplateEntry`, `TemplateRepository`, `ApiGateway` and `TemplateRepositoryException` +are reused unchanged. `pubspec.*`, `lib/main.dart`, the shell, another feature, +`web/`, the Go server and `android/` were not touched. + +## Behaviour and wire requests + +- Exact browser wording: title `Create from {name}` (blank name falls back to the + template key), field `New pipeline name (required)`, note + `Creates a new draft pipeline on the server from this template's source; it is not run.`, + buttons `Cancel`/`Create`, in-flight `Creating…`, post-success `Close`, and + `Created "{name}". It is in the Pipelines list.`. +- Opening the prompt, typing and Cancel send nothing. Only Create runs + `TemplateRepository.validate(template.source)` and then, only after it passes, + `TemplateRepository.submit(typedName, template.source)`. The repository sends + `{type: 'submit', name: , source: , create_only: true}`; the + source is never trimmed or re-encoded. +- Blank/whitespace-only name keeps Create disabled. Sending disables the field, + both buttons and the confirm action, and blocks back/barrier dismissal. After a + success the field and Create stay disabled and the dismiss button reads Close. +- `_sending` plus `_canSubmit` guard a second tap/Enter, so a pending validate + cannot produce a second validate or submit. +- A validation refusal shows the server's own text in the still-open prompt and + sends no `submit`. A submit refusal also keeps the prompt and the typed name. + Neither refusal calls the callback and neither shows a success line. +- Success uses the server's own `detail.name` when non-blank, else the trimmed + submitted name, exactly like the web's `createdPipelineName`. The accepted + `detail` is delivered through `onCreated` once, before the user presses Close. +- The field keeps one layout on both hosts: a wrapping visible label, then the + native `TextField`/`CupertinoTextField`, wrapped in `MergeSemantics`. A reader + gets one text-field node whose label is the full wording and whose value is the + typed name. Refusal/success is placed after the field and before the note. +- Controls are standard `AlertDialog`/`AlertDialog.scrollable`/`TextField`/ + `FilledButton`/`TextButton` and `CupertinoAlertDialog`/`CupertinoTextField`/ + `CupertinoDialogAction`. Only the semantic error colours are used + (`colorScheme.error`, `CupertinoColors.systemRed`); there are no font/size/ + colour overrides, fixed component sizes or bespoke palette. + +## Checks actually run + +``` +cd app +flutter analyze # No issues found! (1.2s) +dart format --output=none --set-exit-if-changed \ + lib/features/templates test/features/templates \ + tool/template_create_probe.dart # 0 changed +flutter test test/features/templates # 23 passed +flutter test # whole app, passed +flutter build web -o build/web-normal # normal entry, ✓ Built +flutter build web --target=tool/template_create_probe.dart \ + -o build/template_create_probe_web # ✓ Built +PROBE_WEB_ROOT="$PWD/build/template_create_probe_web" \ + OPENCODE_ARTIFACT_DIR=…/public/t1-create \ + node tool/template_create_probe.mjs # ok: true +PROBE_WIDTH=360 PROBE_HEIGHT=640 PROBE_SCALE=2 \ + PROBE_CAPTURE_PREFIX=t1-create-2x-360x640 … # ok: true +PROBE_SCALE=2 PROBE_CAPTURE_PREFIX=t1-create-2x-390x844 … # ok: true +PROBE_HOST=cupertino PROBE_CAPTURE_PREFIX=t1-create-cupertino … # ok: true +git status --porcelain=v1 -uall # only the ten new files below +``` + +The focused suite is the prior T1a data tests (13) plus ten UI/wording tests, +including: blank/Cancel/happy path; validate and submit refusals; the in-flight +lock (disabled field/Cancel, back does not dismiss) and double-submit guard; +Cupertino native controls with the visible label; 2x/360×640 feedback visible at +rest for both refusal and success; the full label wrapping without ellipsis; the +reveal after the content was scrolled; and the field's semantics label + value on +both hosts. + +## Browser evidence (real headless Chrome, loopback only) + +The fixture gateway is in-process; the probe never opens a socket and never +submits to a real server. The driver reads `globalThis.templateCreateProbe` to +verify request counts and payloads, and asserts the field's DOM `aria-label` is +`New pipeline name (required)`. + +1x, 390×844 (`public/t1-create/`): + +- Blank name: `Create` had `aria-disabled="true"`, field empty, editable and + labelled. +- `Probe release` + Create: exactly one `validate`, zero `submit`, callback + count 0; the server's `invalid definition: fixture stage "añadir" has no type` + was shown and the field still held `Probe release`. +- Retrying Create: second `validate`, exactly one `submit` with + `{name: "Probe release", source: , create_only: true}`, one + created callback, the exact success line, field locked, `Close` shown. +- Close sent no further request and dismissed the prompt. + +2x captures (`public/t1-create-2x-360x640/`, `public/t1-create-2x-390x844/`): + +- The full `New pipeline name (required)` label wraps and is visible at rest on + both viewports; the refusal and success lines are visible at rest on 360×640 + without scrolling or any other interaction. +- The title remains visible above them; only the note is clipped by the short + viewport, and it stays scrollable. + +Cupertino captures (`public/t1-create-cupertino/`, 390×844, Chrome): blank, +refusal and success with the same label, wording, request counts and locked +field. The DOM input exposes `aria-label` `New pipeline name (required)`. + +Captures (public, shared with later stages): + +- `public/t1-create/t1-create-blank-name-disabled.png` +- `public/t1-create/t1-create-validation-refusal.png` +- `public/t1-create/t1-create-accepted-success.png` +- `public/t1-create-2x-360x640/t1-create-2x-360x640-blank-name-disabled.png` +- `public/t1-create-2x-360x640/t1-create-2x-360x640-validation-refusal.png` +- `public/t1-create-2x-360x640/t1-create-2x-360x640-accepted-success.png` +- `public/t1-create-2x-390x844/t1-create-2x-390x844-blank-name-disabled.png` +- `public/t1-create-2x-390x844/t1-create-2x-390x844-validation-refusal.png` +- `public/t1-create-2x-390x844/t1-create-2x-390x844-accepted-success.png` +- `public/t1-create-cupertino/t1-create-cupertino-blank-name-disabled.png` +- `public/t1-create-cupertino/t1-create-cupertino-validation-refusal.png` +- `public/t1-create-cupertino/t1-create-cupertino-accepted-success.png` + +The probe defaults to the Material host; `PROBE_HOST=cupertino`, +`PROBE_WIDTH`/`PROBE_HEIGHT`, `PROBE_SCALE` and `PROBE_CAPTURE_PREFIX` select the +other evidence above. The driver types the name once and retries Create after the +server refusal, so the same typed name is retained and then accepted. + +## Task diff + +``` +?? app/lib/features/templates/ui/template_create_dialog.dart +?? app/lib/features/templates/ui/template_create_wording.dart +?? app/notes/T1-create.md +?? app/test/features/templates/ui/template_create_accessibility_test.dart +?? app/test/features/templates/ui/template_create_dialog_test.dart +?? app/test/features/templates/ui/template_create_flow_test.dart +?? app/test/features/templates/ui/template_create_test_support.dart +?? app/test/features/templates/ui/template_create_wording_test.dart +?? app/tool/template_create_probe.dart +?? app/tool/template_create_probe.mjs +``` + +All changes are additions in the working tree; no tracked file was modified and +no other lane's work was changed. Nothing was staged, committed, pushed or +deployed. + +## Honest limits + +- Not wired into a gallery or shell: this slice exposes + `showTemplateCreateDialog(...)`, as instructed. The manager owns registration + and the real detail action. +- Mobile (Android/iOS) is unverified: no Android/iOS build, emulator, device or + ADB was used. The Cupertino captures are Chrome's rendering of the Cupertino + widgets, not iOS; VoiceOver/TalkBack behaviour was not run. +- No real Pipelines server, credentials or operator pipeline was touched. Browser + evidence uses the in-process fixture gateway and no `submit` reached a server. +- The app's real dark shell theme was not exercised; both native hosts use + semantic theme colours (the Cupertino capture happened to run in dark mode). +- Not committed/pushed/deployed; the candidate is the uncommitted working tree + above. diff --git a/app/test/features/templates/ui/template_create_accessibility_test.dart b/app/test/features/templates/ui/template_create_accessibility_test.dart new file mode 100644 index 00000000..3c664a46 --- /dev/null +++ b/app/test/features/templates/ui/template_create_accessibility_test.dart @@ -0,0 +1,225 @@ +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/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/templates/ui/template_create_wording.dart'; + +import 'template_create_test_support.dart'; + +/// A 360×640 phone: the short viewport a large text scale runs out of room on. +void _shortPhone(WidgetTester tester) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(360, 640); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); +} + +/// The Material scrollable region between the title and the pinned actions. +Rect _contentViewport(WidgetTester tester) => tester.getRect( + find + .descendant( + of: find.byType(AlertDialog), + matching: find.byType(SingleChildScrollView), + ) + .first, +); + +void _expectInside(Rect viewport, Rect child, String what) { + expect( + child.top, + greaterThanOrEqualTo(viewport.top - 0.5), + reason: '$what is scrolled above the visible content', + ); + expect( + child.bottom, + lessThanOrEqualTo(viewport.bottom + 0.5), + reason: '$what is below the visible content', + ); +} + +void main() { + testWidgets( + 'at 2x on a short phone the full label and a refusal are visible without ' + 'scrolling', + (tester) async { + _shortPhone(tester); + const refusal = 'invalid definition: fixture stage "añadir" has no type'; + final gateway = FakeTemplateCreateGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + await tester.pumpWidget( + templateCreateApp( + TemplateCreateHost(gateway: gateway, onCreated: (_) {}), + textScale: 2, + ), + ); + + await tester.tap(find.byKey(templateCreateOpenKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + + final label = find.text(templateCreateNameLabel); + expect(label, findsOneWidget); + final paragraph = tester.renderObject(label); + expect(paragraph.text.toPlainText(), templateCreateNameLabel); + expect( + paragraph.didExceedMaxLines, + isFalse, + reason: 'the required suffix must not be ellipsized', + ); + final unscaled = TextPainter( + text: paragraph.text, + textDirection: paragraph.textDirection, + textScaler: paragraph.textScaler, + )..layout(); + expect( + unscaled.width, + greaterThan(paragraph.size.width), + reason: 'at 2x the label wraps instead of shrinking to one line', + ); + unscaled.dispose(); + + await tester.enterText( + find.byKey(templateCreateNameKey), + 'Narrow attempt', + ); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pumpAndSettle(); + + expect(find.text(refusal), findsOneWidget); + _expectInside( + _contentViewport(tester), + tester.getRect(find.byKey(templateCreateErrorKey)), + 'the validation refusal', + ); + expect(gateway.calls.map((call) => call.type), ['validate']); + }, + ); + + testWidgets('at 2x on a short phone the accepted line is visible without ' + 'scrolling', (tester) async { + _shortPhone(tester); + final gateway = FakeTemplateCreateGateway(acceptedTemplateCreate); + final created = []; + await tester.pumpWidget( + templateCreateApp( + TemplateCreateHost(gateway: gateway, onCreated: created.add), + textScale: 2, + ), + ); + + await tester.tap(find.byKey(templateCreateOpenKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(templateCreateNameKey), 'Probe release'); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect( + find.byKey(templateCreateSuccessKey), + findsOneWidget, + reason: 'the success line is shown, not merely off-screen', + ); + _expectInside( + _contentViewport(tester), + tester.getRect(find.byKey(templateCreateSuccessKey)), + 'the accepted create line', + ); + expect(created.single, {'id': 1, 'name': 'Server name'}); + }); + + testWidgets('a refusal is revealed after the content was scrolled away', ( + tester, + ) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(320, 480); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + const refusal = 'invalid stage'; + final gateway = FakeTemplateCreateGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + await tester.pumpWidget( + templateCreateApp( + TemplateCreateHost(gateway: gateway, onCreated: (_) {}), + textScale: 3, + ), + ); + + await tester.tap(find.byKey(templateCreateOpenKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(templateCreateNameKey), 'Scrolled away'); + await tester.pump(); + // Scroll the prompt content to its end, as a reader would. + final position = tester + .state( + find + .descendant( + of: find.byType(SingleChildScrollView), + matching: find.byType(Scrollable), + ) + .first, + ) + .position; + expect( + position.maxScrollExtent, + greaterThan(0), + reason: 'the 3x content must overflow for this check to mean anything', + ); + position.jumpTo(position.maxScrollExtent); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pumpAndSettle(); + + expect(find.text(refusal), findsOneWidget); + final viewport = _contentViewport(tester); + final feedback = tester.getRect(find.byKey(templateCreateErrorKey)); + // At 3x the message can be taller than the viewport; its start must still + // be brought back into view after the content was scrolled away. + expect( + feedback.top, + greaterThanOrEqualTo(viewport.top - 0.5), + reason: 'the refusal is scrolled above the visible content', + ); + expect( + feedback.top, + lessThan(viewport.bottom), + reason: 'the refusal start is below the visible content', + ); + }); + + testWidgets('the name field is labelled for screen readers on both hosts', ( + tester, + ) async { + final handle = tester.ensureSemantics(); + for (final cupertino in [false, true]) { + await tester.pumpWidget( + templateCreateApp( + TemplateCreateHost( + gateway: FakeTemplateCreateGateway(acceptedTemplateCreate), + onCreated: (_) {}, + cupertino: cupertino, + ), + cupertino: cupertino, + textScale: 2, + ), + ); + await tester.tap(find.byKey(templateCreateOpenKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(templateCreateNameKey), 'Scaled'); + await tester.pump(); + + final data = tester + .getSemantics(find.byKey(templateCreateNameKey)) + .getSemanticsData(); + expect(data.label, templateCreateNameLabel); + expect(data.value, 'Scaled'); + expect(data.flagsCollection.isTextField, isTrue); + } + handle.dispose(); + }); +} diff --git a/app/test/features/templates/ui/template_create_dialog_test.dart b/app/test/features/templates/ui/template_create_dialog_test.dart new file mode 100644 index 00000000..bb1800dd --- /dev/null +++ b/app/test/features/templates/ui/template_create_dialog_test.dart @@ -0,0 +1,138 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/templates/ui/template_create_wording.dart'; + +import '../data/template_test_support.dart' show source; +import 'template_create_test_support.dart'; + +void main() { + testWidgets( + 'material prompt keeps blank Create disabled, Cancel sends nothing and ' + 'Create validates then submits the trimmed name and verbatim source', + (tester) async { + final gateway = FakeTemplateCreateGateway(acceptedTemplateCreate); + final created = []; + await tester.pumpWidget( + templateCreateApp( + TemplateCreateHost(gateway: gateway, onCreated: created.add), + ), + ); + + await tester.tap(find.byKey(templateCreateOpenKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text('Create from Starter template'), findsOneWidget); + expect(find.text(templateCreateNameLabel), findsOneWidget); + expect(find.text(templateCreateNote), findsOneWidget); + expect(materialTemplateName(tester), ''); + expect( + tester + .widget(find.byKey(templateCreateConfirmKey)) + .onPressed, + isNull, + ); + + await tester.enterText(find.byKey(templateCreateNameKey), ' '); + await tester.pump(); + expect( + tester + .widget(find.byKey(templateCreateConfirmKey)) + .onPressed, + isNull, + ); + + await tester.enterText(find.byKey(templateCreateNameKey), ' Café '); + await tester.pump(); + expect( + tester + .widget(find.byKey(templateCreateConfirmKey)) + .onPressed, + isNotNull, + ); + await tester.tap(find.byKey(templateCreateCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + expect(created, isEmpty); + + await tester.tap(find.byKey(templateCreateOpenKey)); + await tester.pumpAndSettle(); + expect(materialTemplateName(tester), ''); + await tester.enterText(find.byKey(templateCreateNameKey), ' Café '); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['validate', 'submit']); + expect(gateway.calls[0].fields, {'source': source}); + expect(gateway.calls[1].fields, { + 'name': 'Café', + 'source': source, + 'create_only': true, + }); + expect(gateway.calls[1].fields.keys, ['name', 'source', 'create_only']); + expect( + find.text('Created "Server name". It is in the Pipelines list.'), + findsOneWidget, + ); + expect(created.single, {'id': 1, 'name': 'Server name'}); + expect( + tester.widget(find.byKey(templateCreateNameKey)).enabled, + isFalse, + ); + expect(find.text('Close'), findsOneWidget); + expect( + tester + .widget(find.byKey(templateCreateConfirmKey)) + .onPressed, + isNull, + ); + + await tester.tap(find.byKey(templateCreateCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(created, hasLength(1)); + }, + ); + + testWidgets( + 'a validation refusal sends no submit, keeps the typed name and shows ' + 'the server error', + (tester) async { + const refusal = 'invalid stage "añadir": unknown key'; + final gateway = FakeTemplateCreateGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + final created = []; + await tester.pumpWidget( + templateCreateApp( + TemplateCreateHost(gateway: gateway, onCreated: created.add), + ), + ); + + await tester.tap(find.byKey(templateCreateOpenKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(templateCreateNameKey), 'Keep me'); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['validate']); + expect(gateway.calls.single.fields, {'source': source}); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(templateCreateErrorKey), findsOneWidget); + expect(find.byKey(templateCreateSuccessKey), findsNothing); + expect(materialTemplateName(tester), 'Keep me'); + expect(created, isEmpty); + expect(find.byType(AlertDialog), findsOneWidget); + expect( + tester + .widget(find.byKey(templateCreateConfirmKey)) + .onPressed, + isNotNull, + ); + }, + ); +} diff --git a/app/test/features/templates/ui/template_create_flow_test.dart b/app/test/features/templates/ui/template_create_flow_test.dart new file mode 100644 index 00000000..bc501268 --- /dev/null +++ b/app/test/features/templates/ui/template_create_flow_test.dart @@ -0,0 +1,171 @@ +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/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/templates/ui/template_create_wording.dart'; + +import '../data/template_test_support.dart' show source; +import 'template_create_test_support.dart'; + +void main() { + testWidgets('a submit refusal keeps the prompt and the typed name', ( + tester, + ) async { + const refusal = 'a pipeline named "Release" already exists'; + final gateway = FakeTemplateCreateGateway((type, fields) async { + if (type == 'validate') return {'graph': {}}; + throw const ProtocolError(refusal); + }); + final created = []; + await tester.pumpWidget( + templateCreateApp( + TemplateCreateHost(gateway: gateway, onCreated: created.add), + ), + ); + + await tester.tap(find.byKey(templateCreateOpenKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(templateCreateNameKey), 'Release'); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['validate', 'submit']); + expect(find.text(refusal), findsOneWidget); + expect(materialTemplateName(tester), 'Release'); + expect(created, isEmpty); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text('Cancel'), findsOneWidget); + expect( + tester.widget(find.byKey(templateCreateNameKey)).enabled, + isTrue, + ); + }); + + testWidgets('a pending validate guards a double submit', (tester) async { + final validate = Completer(); + final submit = Completer(); + var validates = 0; + final gateway = FakeTemplateCreateGateway((type, fields) { + if (type == 'validate') { + validates++; + return validate.future; + } + return submit.future; + }); + final created = []; + await tester.pumpWidget( + templateCreateApp( + TemplateCreateHost(gateway: gateway, onCreated: created.add), + ), + ); + + await tester.tap(find.byKey(templateCreateOpenKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(templateCreateNameKey), 'Only once'); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pump(); + expect(validates, 1); + expect(gateway.calls.where((call) => call.type == 'submit'), isEmpty); + expect(find.text(templateCreateSendingLabel), findsOneWidget); + // In flight the prompt cannot be dismissed or edited. + expect( + tester.widget(find.byKey(templateCreateNameKey)).enabled, + isFalse, + ); + expect( + tester.widget(find.byKey(templateCreateCancelKey)).onPressed, + isNull, + ); + await tester.binding.handlePopRoute(); + await tester.pump(); + expect(find.byType(AlertDialog), findsOneWidget); + + validate.complete({'graph': {}}); + await tester.pump(); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pump(); + expect(gateway.calls.where((call) => call.type == 'submit'), hasLength(1)); + expect( + gateway.calls.where((call) => call.type == 'validate'), + hasLength(1), + ); + + submit.complete({ + 'detail': {'id': 2, 'name': 'Only once'}, + }); + await tester.pumpAndSettle(); + expect(created.single, {'id': 2, 'name': 'Only once'}); + expect( + find.text('Created "Only once". It is in the Pipelines list.'), + findsOneWidget, + ); + }); + + testWidgets('cupertino prompt uses native controls for the same flow', ( + tester, + ) async { + final gateway = FakeTemplateCreateGateway( + (type, fields) async => type == 'validate' + ? {'graph': {}} + : { + 'detail': {'id': 3}, + }, + ); + final created = []; + await tester.pumpWidget( + templateCreateApp( + TemplateCreateHost( + gateway: gateway, + onCreated: created.add, + cupertino: true, + ), + cupertino: true, + ), + ); + + await tester.tap(find.byKey(templateCreateOpenKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byType(CupertinoTextField), findsOneWidget); + expect(find.text(templateCreateNameLabel), findsOneWidget); + expect(cupertinoTemplateName(tester), ''); + expect( + tester + .widget(find.byKey(templateCreateConfirmKey)) + .onPressed, + isNull, + ); + + await tester.enterText(find.byKey(templateCreateNameKey), ' Unicode 🚀 '); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['validate', 'submit']); + expect(gateway.calls[1].fields, { + 'name': 'Unicode 🚀', + 'source': source, + 'create_only': true, + }); + expect( + find.text('Created "Unicode 🚀". It is in the Pipelines list.'), + findsOneWidget, + ); + expect(created.single, {'id': 3}); + expect( + tester + .widget(find.byKey(templateCreateNameKey)) + .enabled, + isFalse, + ); + expect(find.text('Close'), findsOneWidget); + }); +} diff --git a/app/test/features/templates/ui/template_create_test_support.dart b/app/test/features/templates/ui/template_create_test_support.dart new file mode 100644 index 00000000..ceccf019 --- /dev/null +++ b/app/test/features/templates/ui/template_create_test_support.dart @@ -0,0 +1,127 @@ +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/data/template_repository.dart'; +import 'package:pipelines_app/features/templates/domain/template_entry.dart'; +import 'package:pipelines_app/features/templates/ui/template_create_dialog.dart'; +import 'package:pipelines_app/features/templates/ui/template_create_wording.dart'; + +import '../data/template_test_support.dart' show source; + +typedef TemplateCreateHandler = + Future Function(String type, JsonMap fields); + +/// A recording gateway whose replies are supplied per request type. +class FakeTemplateCreateGateway implements ApiGateway { + FakeTemplateCreateGateway(this.handler); + + final TemplateCreateHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +const templateCreateFixture = TemplateEntry( + key: 'starter', + name: 'Starter template', + description: 'A fixture template', + source: source, + scheduled: false, + raw: {}, +); + +const templateCreateOpenKey = ValueKey('open-template-create'); + +String materialTemplateName(WidgetTester tester) => tester + .widget(find.byKey(templateCreateNameKey)) + .controller! + .text; + +String cupertinoTemplateName(WidgetTester tester) => tester + .widget(find.byKey(templateCreateNameKey)) + .controller! + .text; + +Future acceptedTemplateCreate(String type, JsonMap fields) async { + if (type == 'validate') { + return {'graph': {}}; + } + if (type == 'submit') { + return { + 'detail': {'id': 1, 'name': 'Server name'}, + }; + } + throw StateError('Unexpected request $type'); +} + +/// Opens the prompt from a normal button, like a detail's action would. +class TemplateCreateHost extends StatelessWidget { + const TemplateCreateHost({ + super.key, + required this.gateway, + required this.onCreated, + this.cupertino = false, + this.template = templateCreateFixture, + }); + + final FakeTemplateCreateGateway gateway; + final ValueChanged onCreated; + final bool cupertino; + final TemplateEntry template; + + void _open(BuildContext context) { + showTemplateCreateDialog( + context: context, + template: template, + repository: TemplateRepository(gateway), + cupertino: cupertino, + onCreated: onCreated, + ); + } + + @override + Widget build(BuildContext context) { + final body = Center( + child: cupertino + ? CupertinoButton( + key: templateCreateOpenKey, + onPressed: () => _open(context), + child: const Text('Open'), + ) + : FilledButton( + key: templateCreateOpenKey, + onPressed: () => _open(context), + child: const Text('Open'), + ), + ); + if (cupertino) { + return CupertinoPageScaffold(child: body); + } + return Scaffold(body: body); + } +} + +Widget templateCreateApp( + Widget child, { + bool cupertino = false, + double textScale = 1, +}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + return cupertino + ? CupertinoApp(builder: media, home: child) + : MaterialApp(builder: media, home: child); +} diff --git a/app/test/features/templates/ui/template_create_wording_test.dart b/app/test/features/templates/ui/template_create_wording_test.dart new file mode 100644 index 00000000..7c4734b8 --- /dev/null +++ b/app/test/features/templates/ui/template_create_wording_test.dart @@ -0,0 +1,43 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/templates/domain/template_entry.dart'; +import 'package:pipelines_app/features/templates/ui/template_create_wording.dart'; + +import '../data/template_test_support.dart' show source; +import 'template_create_test_support.dart'; + +void main() { + test('the browser wording and name fallbacks stay exact', () { + const unnamed = TemplateEntry( + key: 'starter-key', + name: ' ', + description: '', + source: source, + scheduled: false, + raw: {}, + ); + expect(templateCreateTitle(unnamed), 'Create from starter-key'); + expect( + templateCreateTitle(templateCreateFixture), + 'Create from Starter template', + ); + expect( + templateCreatedName({'name': ' From server '}, 'Typed'), + 'From server', + ); + expect(templateCreatedName({'name': ' '}, ' Typed '), 'Typed'); + expect(templateCreatedName({}, ' Typed '), 'Typed'); + expect( + templateCreateSuccess('Release'), + 'Created "Release". It is in the Pipelines list.', + ); + expect( + describeTemplateCreateError(const ProtocolError('server words')), + 'server words', + ); + expect( + describeTemplateCreateError(''), + 'The server did not create the pipeline.', + ); + }); +} diff --git a/app/tool/template_create_probe.dart b/app/tool/template_create_probe.dart new file mode 100644 index 00000000..94776fda --- /dev/null +++ b/app/tool/template_create_probe.dart @@ -0,0 +1,167 @@ +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/data/template_repository.dart'; +import 'package:pipelines_app/features/templates/domain/template_entry.dart'; +import 'package:pipelines_app/features/templates/ui/template_create_dialog.dart'; + +/// Browser capture entrypoint for the create-from-template prompt. +/// +/// The fixture gateway is in-process and records every request; nothing here +/// opens a socket or contacts a real server. The state published at +/// `globalThis.templateCreateProbe` is read by the probe driver, so it can +/// prove that a validation refusal sent no submit and that an accepted create +/// was reported once. +const _source = ' name: "release"\n stages:\n - key: "añadir" 😀 \n'; + +class _ProbeGateway implements ApiGateway { + _ProbeGateway(this.publish); + + final VoidCallback publish; + int validates = 0; + int submits = 0; + bool failNextValidate = true; + String? lastSource; + JsonMap? lastSubmit; + final List created = []; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type == 'validate') { + validates++; + lastSource = fields['source'] as String?; + publish(); + if (failNextValidate) { + failNextValidate = false; + throw const ProtocolError( + 'invalid definition: fixture stage "añadir" has no type', + ); + } + return { + 'graph': {'stages': []}, + }; + } + if (type == 'submit') { + submits++; + lastSubmit = Map.from(fields); + publish(); + return { + 'detail': {'id': 71, 'name': 'Probe release'}, + }; + } + throw StateError('The create probe does not implement $type'); + } +} + +void main() => runApp(const _ProbeApp()); + +class _ProbeApp extends StatelessWidget { + const _ProbeApp(); + + @override + Widget build(BuildContext context) { + final params = Uri.base.queryParameters; + final cupertino = params['host'] == 'cupertino'; + final scale = double.tryParse(params['scale'] ?? '') ?? 1; + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: scaled, + home: const _ProbeHome(cupertino: true), + ); + } + return MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + builder: scaled, + home: const _ProbeHome(cupertino: false), + ); + } +} + +class _ProbeHome extends StatefulWidget { + const _ProbeHome({required this.cupertino}); + + final bool cupertino; + + @override + State<_ProbeHome> createState() => _ProbeHomeState(); +} + +class _ProbeHomeState extends State<_ProbeHome> { + late final _gateway = _ProbeGateway(_publish); + + static const _template = TemplateEntry( + key: 'release', + name: 'Release workflow', + description: 'Fixture template', + source: _source, + scheduled: false, + raw: {}, + ); + + void _publish() { + globalContext.setProperty( + 'templateCreateProbe'.toJS, + { + 'validates': _gateway.validates, + 'submits': _gateway.submits, + 'lastSource': _gateway.lastSource, + 'lastSubmit': _gateway.lastSubmit, + 'created': _gateway.created, + }.jsify(), + ); + } + + Future _open() async { + await showTemplateCreateDialog( + context: context, + template: _template, + repository: TemplateRepository(_gateway), + cupertino: widget.cupertino, + onCreated: (detail) { + _gateway.created.add(detail); + _publish(); + }, + ); + } + + @override + Widget build(BuildContext context) { + if (widget.cupertino) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar( + middle: Text('Template create probe'), + ), + child: Center( + child: CupertinoButton.filled( + onPressed: _open, + child: const Text('Create pipeline from this template'), + ), + ), + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Template create probe')), + body: Center( + child: FilledButton( + key: const ValueKey('template-probe-open'), + onPressed: _open, + child: const Text('Create pipeline from this template'), + ), + ), + ); + } +} diff --git a/app/tool/template_create_probe.mjs b/app/tool/template_create_probe.mjs new file mode 100644 index 00000000..14860200 --- /dev/null +++ b/app/tool/template_create_probe.mjs @@ -0,0 +1,316 @@ +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 create-from-template prompt. +// +// Usage (from app/): +// flutter build web --target=tool/template_create_probe.dart \ +// -o build/template_create_probe_web +// OPENCODE_ARTIFACT_DIR= node tool/template_create_probe.mjs +// +// Optional PROBE_WIDTH/PROBE_HEIGHT (viewport), PROBE_SCALE (text scale), +// PROBE_HOST (material|cupertino) and PROBE_CAPTURE_PREFIX. The bundle's +// fixture gateway is in-process, so this never contacts a real Pipelines +// server and never submits to one. Requires Google Chrome. + +const root = resolve(process.env.PROBE_WEB_ROOT ?? 'build/template_create_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 capturePrefix = process.env.PROBE_CAPTURE_PREFIX ?? 't1-create'; + +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(), 'template-create-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) { + for (let attempt = 0; attempt < 160; 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: 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)}`); + 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 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) => { + const point = await evaluate(`(() => { + const needle = ${JSON.stringify(label)}; + const candidates = [...document.querySelectorAll('flt-semantics')].filter( + (el) => (el.getAttribute('aria-label') || el.innerText || '').trim() === 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(); + return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; + })()`); + if (!point) { + const labels = await evaluate( + "[...document.querySelectorAll('flt-semantics')].map((el) => (el.getAttribute('aria-label') || el.innerText || '').trim()).filter(Boolean)", + ); + throw new Error(`Could not click ${JSON.stringify(label)}. Labels: ${JSON.stringify(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); + }; + + // Null while the prompt is closed; true/false is the Create button's state. + const createDisabled = () => + evaluate(`(() => { + const el = [...document.querySelectorAll('flt-semantics')].find( + (node) => + (node.getAttribute('aria-label') || node.innerText || '').trim() === 'Create' && + node.getAttribute('role') === 'button', + ); + return el ? el.getAttribute('aria-disabled') === 'true' : null; + })()`); + + const field = () => + evaluate(`(() => { + const input = document.querySelector('input'); + return input + ? { value: input.value, disabled: input.disabled, label: input.getAttribute('aria-label') } + : null; + })()`); + + 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.templateCreateProbe ?? 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}` }, session); + await waitFor( + () => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), + 'semantics placeholder', + ); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + await assertBody('Create pipeline from this template'); + + await clickLabel('Create pipeline from this template'); + await waitFor(() => createDisabled().then((value) => value !== null), 'the create prompt'); + await assertBody('Create from Release workflow'); + await assertBody('New pipeline name (required)'); + await assertBody("Creates a new draft pipeline on the server from this template's source; it is not run."); + // CupertinoDialogAction does not expose aria-disabled on the web semantics + // layer; its disabled state is covered by the widget tests. + if (host !== 'cupertino' && (await createDisabled()) !== true) { + throw new Error('Create was not disabled with a blank name'); + } + const blank = await field(); + if (blank?.value !== '' || blank?.disabled !== false) { + throw new Error(`The field is not blank and editable: ${JSON.stringify(blank)}`); + } + if (blank?.label !== 'New pipeline name (required)') { + throw new Error(`The name field has no accessible name: ${JSON.stringify(blank)}`); + } + captures.push(await capture(`${capturePrefix}-blank-name-disabled`)); + checks.push({ check: 'blank name keeps Create disabled', field: blank }); + + await typeName('Probe release'); + if (host !== 'cupertino' && (await createDisabled()) !== false) { + throw new Error('Create stayed disabled after a non-blank name'); + } + await clickLabel('Create'); + await assertBody('invalid definition: fixture stage "añadir" has no type'); + const refused = await state(); + if (refused?.validates !== 1 || refused?.submits !== 0 || refused?.created?.length !== 0) { + throw new Error(`A validation refusal sent more than validate: ${JSON.stringify(refused)}`); + } + if ((await field())?.value !== 'Probe release') { + throw new Error(`The typed name was lost: ${JSON.stringify(await field())}`); + } + captures.push(await capture(`${capturePrefix}-validation-refusal`)); + checks.push({ + check: 'validation refusal sent no submit and kept the typed name', + validates: refused.validates, + submits: refused.submits, + created: refused.created.length, + field: await field(), + }); + + // Retrying the same name is the normal correction after a server refusal. + await clickLabel('Create'); + await assertBody('Created "Probe release". It is in the Pipelines list.'); + const accepted = await state(); + if (accepted?.validates !== 2 || accepted?.submits !== 1 || accepted?.created?.length !== 1) { + throw new Error(`The accepted create was not reported exactly once: ${JSON.stringify(accepted)}`); + } + if (accepted.lastSubmit?.name !== 'Probe release' || accepted.lastSubmit?.create_only !== true) { + throw new Error(`Submit payload drifted: ${JSON.stringify(accepted.lastSubmit)}`); + } + const verbatim = ' name: "release"\n stages:\n - key: "añadir" 😀 \n'; + if (accepted.lastSubmit?.source !== accepted.lastSource || accepted.lastSource !== verbatim) { + throw new Error(`Source was not sent verbatim: ${JSON.stringify(accepted)}`); + } + const done = await field(); + if (done?.disabled !== true) throw new Error(`The field did not lock after success: ${JSON.stringify(done)}`); + await assertBody('Close'); + captures.push(await capture(`${capturePrefix}-accepted-success`)); + checks.push({ + check: 'accepted create showed the exact line, reported once and locked the field', + validates: accepted.validates, + submits: accepted.submits, + created: accepted.created.length, + lastSubmit: accepted.lastSubmit, + field: done, + }); + + await clickLabel('Close'); + await waitFor(async () => (await createDisabled()) === null, 'the prompt to close'); + checks.push({ + check: 'Close dismissed the prompt without another request', + state: await state(), + }); + console.log(JSON.stringify({ ok: true, origin, viewport: { width, height }, textScale, host, 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 }); +}