diff --git a/app/lib/application/app_route.dart b/app/lib/application/app_route.dart index 28518c99..b0e51f2f 100644 --- a/app/lib/application/app_route.dart +++ b/app/lib/application/app_route.dart @@ -2,7 +2,7 @@ /// /// The set mirrors [AppDestination] but stays free of widget imports so the /// parser and serialiser can be exercised without a Flutter host. -enum AppRouteKind { pipelines, runs, chat, search, settings } +enum AppRouteKind { pipelines, runs, chat, search, settings, templates } /// One page route: a destination plus the run it opens, if any. /// @@ -18,6 +18,10 @@ class AppRoute { static const search = AppRoute(AppRouteKind.search); static const settings = AppRoute(AppRouteKind.settings); + /// The template gallery, reached from Settings. It is a Settings sub-page, + /// not a fifth tab, so Back returns to Settings. + static const templates = AppRoute(AppRouteKind.templates); + static const run = _RunRouteFactory(); /// One chat session, or the chat list when [id] is not a session id. @@ -43,6 +47,7 @@ class AppRoute { : '/chat/${Uri.encodeComponent(chatSessionId!)}', AppRouteKind.search => '/search', AppRouteKind.settings => '/settings', + AppRouteKind.templates => '/templates', }; /// Parses a browser pathname (or a full URL) into a route. @@ -81,6 +86,7 @@ class AppRoute { 'chat' when segments.length == 2 => _chatRoute(segments[1]), 'search' when segments.length == 1 => search, 'settings' when segments.length == 1 => settings, + 'templates' when segments.length == 1 => templates, _ => pipelines, }; } diff --git a/app/lib/application/app_router.dart b/app/lib/application/app_router.dart index c93fad94..581c4e78 100644 --- a/app/lib/application/app_router.dart +++ b/app/lib/application/app_router.dart @@ -30,14 +30,23 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { required this.onPopToChat, required this.cupertino, this.searchBuilder, + this.templatesBuilder, AppRoute initial = AppRoute.pipelines, }) : _route = initial, _searchReturn = initial.kind == AppRouteKind.search ? AppRoute.pipelines + : initial, + _templatesReturn = initial.kind == AppRouteKind.templates + ? AppRoute.settings : initial; final Widget Function(BuildContext context, AppRoute route) builder; + /// The Templates page above the shell. Templates belongs to Settings, so the + /// shell keeps the Settings destination mounted underneath and its state is + /// restored when this page closes. + final Widget Function(BuildContext context)? templatesBuilder; + /// The Search page above the shell. Search is transient chrome, not a fifth /// tab: the shell stays mounted underneath so closing restores its loaded /// state and selection, and the standard navigation bar supplies Back. @@ -54,16 +63,22 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { final _navigatorKey = GlobalKey(); static const _pageKey = ValueKey('pipelines-shell'); static const _searchPageKey = ValueKey('app-search'); + static const _templatesPageKey = ValueKey('app-templates'); AppRoute _route; /// The destination that was open before Search, restored on close. AppRoute _searchReturn; + /// The Settings route the Templates page closes back to. + AppRoute _templatesReturn; + AppRoute get route => _route; bool get searchOpen => _route.kind == AppRouteKind.search; + bool get templatesOpen => _route.kind == AppRouteKind.templates; + @override AppRoute get currentConfiguration => _route; @@ -80,11 +95,19 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { @override Widget build(BuildContext context) { final searching = searchOpen && searchBuilder != null; - final shellRoute = searching ? _searchReturn : _route; + final templates = templatesOpen && templatesBuilder != null; + final shellRoute = searching + ? _searchReturn + : templates + ? _templatesReturn + : _route; return Navigator( key: _navigatorKey, pages: [ _page(_pageKey, builder(context, shellRoute)), + // Templates is a Settings sub-page: the shell stays mounted underneath, + // so closing restores Settings exactly as it was left. + if (templates) _page(_templatesPageKey, templatesBuilder!(context)), // Search is a transient full-screen mode, so a full-screen dialog gives // the standard Close/Cancel action instead of a Back chevron. if (searching) @@ -92,10 +115,24 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { ], onDidRemovePage: (page) { if (page.key == _searchPageKey) closeSearch(); + if (page.key == _templatesPageKey) closeTemplates(); }, ); } + /// Open the Templates gallery above Settings. The browser history entry is + /// `/templates`; Back returns to the same Settings screen instance. + void openTemplates() { + if (templatesOpen) return; + _templatesReturn = AppRoute.settings; + goTo(AppRoute.templates); + } + + void closeTemplates() { + if (!templatesOpen) return; + goTo(AppRoute.settings); + } + /// Open Search above the current destination; its route carries the browser /// history entry, and close/back returns to what was open before. void openSearch() { @@ -127,6 +164,10 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { closeSearch(); return true; } + if (templatesOpen) { + closeTemplates(); + return true; + } if (_route.runId != null) { onPopToRuns(); return true; diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 861bd38c..ecbcd4f0 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -18,6 +18,7 @@ import 'pipelines_destination.dart'; import 'runs_destination.dart'; import 'search_destination.dart'; import 'server_endpoint.dart'; +import 'templates_destination.dart'; /// Composes the live application around one [AppSession] and one [Router]. /// @@ -51,6 +52,11 @@ class _PipelinesAppState extends State { late final RouterConfig _config; late final bool _cupertino; + /// Advances when a template create is accepted. The Pipelines destination + /// uses it to re-read through its mounted controller; no row is inserted + /// locally, so the next list reply is the only source of the new pipeline. + int _pipelinesRefresh = 0; + @override void initState() { super.initState(); @@ -77,6 +83,7 @@ class _PipelinesAppState extends State { onPopToRuns: () => _delegate.goTo(AppRoute.runs), onPopToChat: () => _delegate.goTo(AppRoute.chat), searchBuilder: _buildSearch, + templatesBuilder: _buildTemplates, builder: _buildShell, ); _config = RouterConfig( @@ -122,6 +129,22 @@ class _PipelinesAppState extends State { if (runId != null) _delegate.goTo(AppRoute.run(runId)); } + /// The Templates page above Settings. Closing it restores the same Settings + /// screen instance, so an edited field or an open connection state survives. + Widget _buildTemplates(BuildContext context) => TemplatesDestination( + session: _session, + server: widget.server, + onBack: _delegate.closeTemplates, + onCreated: _templateCreated, + ); + + /// An accepted create only invalidates Pipelines; the list is re-read and the + /// new row appears from the server's reply, never from an optimistic insert. + void _templateCreated(JsonMap _) { + if (!mounted) return; + setState(() => _pipelinesRefresh++); + } + Widget _buildShell(BuildContext context, AppRoute route) => AdaptiveShell( cupertino: _cupertino, destination: _destinationOf(route.kind), @@ -129,8 +152,11 @@ class _PipelinesAppState extends State { _delegate.goTo(_routeOf(destination)), onSearch: _delegate.openSearch, destinationBodies: { - AppDestination.pipelines: (_) => - PipelinesDestination(session: _session, server: widget.server), + AppDestination.pipelines: (_) => PipelinesDestination( + session: _session, + server: widget.server, + refreshToken: _pipelinesRefresh, + ), AppDestination.runs: (_) => RunsDestination( session: _session, server: widget.server, @@ -149,6 +175,7 @@ class _PipelinesAppState extends State { client: _session.client, initialEndpoint: _session.endpoint, embedded: true, + onOpenTemplates: _delegate.openTemplates, ), }, ); @@ -160,6 +187,8 @@ class _PipelinesAppState extends State { // Search is a transient page above the shell; it never becomes a tab. AppRouteKind.search => AppDestination.pipelines, AppRouteKind.settings => AppDestination.settings, + // Templates is a Settings sub-page, not a fifth tab. + AppRouteKind.templates => AppDestination.settings, }; AppRoute _routeOf(AppDestination destination) => switch (destination) { diff --git a/app/lib/application/pipelines_destination.dart b/app/lib/application/pipelines_destination.dart index d9b3c603..92b1977e 100644 --- a/app/lib/application/pipelines_destination.dart +++ b/app/lib/application/pipelines_destination.dart @@ -17,11 +17,17 @@ class PipelinesDestination extends StatelessWidget { super.key, required this.session, required this.server, + this.refreshToken = 0, }); final AppSession session; final ServerEndpoint server; + /// Requests a fresh list/detail read without remounting the screen or losing + /// the open pipeline. The shell advances it when a template create was + /// accepted; the rows still come only from the server's next reply. + final int refreshToken; + @override Widget build(BuildContext context) => AnimatedBuilder( animation: session, @@ -56,6 +62,8 @@ class PipelinesDestination extends StatelessWidget { Widget _pipelinesScreen() => PipelinesScreen( gateway: session.gateway, embedded: true, - syncToken: session.connectionEpoch, + // A reconnect or an accepted template create both advance this counter; + // either change re-reads through the mounted controller. + syncToken: session.connectionEpoch + refreshToken, ); } diff --git a/app/lib/application/templates_destination.dart b/app/lib/application/templates_destination.dart new file mode 100644 index 00000000..343992ce --- /dev/null +++ b/app/lib/application/templates_destination.dart @@ -0,0 +1,122 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../core/api_gateway.dart'; +import '../features/templates/screen.dart'; +import '../ui/adaptive/host.dart'; +import 'app_session.dart'; +import 'connection_status.dart'; +import 'server_endpoint.dart'; + +/// The Back control of the app-level Templates page. +const templatesPageBackKey = ValueKey('templates-page-back'); + +/// The Templates destination: the landed gallery over the app's shared gateway. +/// +/// The gallery is rendered in embedded mode, so the shell owns navigation; this +/// destination contributes the page's one native bar (Back + Templates) and the +/// same honest connection states as the other destinations. No socket is opened +/// here: [session] owns the only connection, and a template read, validate or +/// create request travels over it. +/// +/// [onCreated] forwards the server-confirmed detail once, so the caller can +/// invalidate the Pipelines list. This screen never inserts a row itself. +class TemplatesDestination extends StatelessWidget { + const TemplatesDestination({ + super.key, + required this.session, + required this.server, + required this.onBack, + this.onCreated, + }); + + final AppSession session; + final ServerEndpoint server; + + /// Closes this page and restores the Settings destination underneath. + final VoidCallback onBack; + final ValueChanged? onCreated; + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + return AnimatedBuilder( + animation: session, + builder: (context, _) => _TemplatesPage( + cupertino: cupertino, + onBack: onBack, + child: _body(cupertino), + ), + ); + } + + Widget _body(bool cupertino) { + if (!session.everConnected) { + return ConnectionGate( + session: session, + server: server, + cupertino: cupertino, + ); + } + return Column( + children: [ + if (!session.connected) + ConnectionBanner(session: session, cupertino: cupertino), + Expanded( + child: TemplatesScreen( + gateway: session.gateway, + embedded: true, + onCreated: onCreated, + ), + ), + ], + ); + } +} + +/// The page's standard native bar. Back is named explicitly so it cannot be +/// confused with the gallery's own Back-to-gallery control. +class _TemplatesPage extends StatelessWidget { + const _TemplatesPage({ + required this.cupertino, + required this.onBack, + required this.child, + }); + + final bool cupertino; + final VoidCallback onBack; + final Widget child; + + @override + Widget build(BuildContext context) { + if (cupertino) { + return CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar( + leading: CupertinoButton( + key: templatesPageBackKey, + padding: EdgeInsets.zero, + onPressed: onBack, + child: const Icon( + CupertinoIcons.back, + semanticLabel: 'Back to Settings', + ), + ), + middle: const Text('Templates'), + ), + child: SafeArea(child: child), + ); + } + return Scaffold( + appBar: AppBar( + leading: IconButton( + key: templatesPageBackKey, + tooltip: 'Back to Settings', + onPressed: onBack, + icon: const Icon(Icons.arrow_back), + ), + title: const Text('Templates'), + ), + body: SafeArea(child: child), + ); + } +} diff --git a/app/lib/features/settings/settings_keys.dart b/app/lib/features/settings/settings_keys.dart index 47575721..7629b9a7 100644 --- a/app/lib/features/settings/settings_keys.dart +++ b/app/lib/features/settings/settings_keys.dart @@ -9,4 +9,5 @@ abstract final class SettingsKeys { static const reconnect = ValueKey('settings.reconnect'); static const workspace = ValueKey('settings.workspace'); static const saveWorkspace = ValueKey('settings.saveWorkspace'); + static const templates = ValueKey('settings.templates'); } diff --git a/app/lib/features/settings/settings_screen.dart b/app/lib/features/settings/settings_screen.dart index 13891ca4..9984f77c 100644 --- a/app/lib/features/settings/settings_screen.dart +++ b/app/lib/features/settings/settings_screen.dart @@ -10,6 +10,7 @@ import 'settings_controls.dart'; import 'settings_layout.dart'; import 'settings_sections.dart'; import 'settings_store.dart'; +import 'settings_templates_section.dart'; /// The Settings destination: the server connection and the server-side /// workspace, in native Material (native platforms) or Cupertino (iOS) controls. @@ -27,6 +28,7 @@ class SettingsScreen extends StatefulWidget { this.store, this.ping, this.embedded = false, + this.onOpenTemplates, }); final transport.PipelinesClient client; @@ -44,6 +46,10 @@ class SettingsScreen extends StatefulWidget { /// The application shell already owns the native navigation bar and safe area. final bool embedded; + /// Opens the Templates gallery. Null keeps Settings standalone/incomplete + /// without a dead row that would go nowhere. + final VoidCallback? onOpenTemplates; + @override State createState() => _SettingsScreenState(); } @@ -121,6 +127,12 @@ class _SettingsScreenState extends State { controller: _controller, workspaceField: _workspaceField, ), + if (widget.onOpenTemplates != null) ...[ + const SizedBox(height: settingsSectionGap), + const _SectionTitle('Templates'), + const SizedBox(height: settingsTitleGap), + SettingsTemplatesSection(onOpen: widget.onOpenTemplates!), + ], ], ), ), diff --git a/app/lib/features/settings/settings_templates_section.dart b/app/lib/features/settings/settings_templates_section.dart new file mode 100644 index 00000000..db911426 --- /dev/null +++ b/app/lib/features/settings/settings_templates_section.dart @@ -0,0 +1,50 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'settings_keys.dart'; +import 'settings_theme.dart'; + +/// The Settings entry to the Templates gallery. +/// +/// The row wording matches the current web Settings page: `Browse templates` +/// with the server-catalogue secondary line, under its `Templates` heading. It +/// only opens the route; loading the catalogue is the gallery's own read. +const String settingsTemplatesLabel = 'Browse templates'; +const String settingsTemplatesSecondary = + 'Reusable pipeline definitions offered by the server.'; + +class SettingsTemplatesSection extends StatelessWidget { + const SettingsTemplatesSection({super.key, required this.onOpen}); + + final VoidCallback onOpen; + + @override + Widget build(BuildContext context) { + if (usesCupertinoControls(context)) { + return CupertinoListSection.insetGrouped( + margin: EdgeInsets.zero, + children: [ + CupertinoListTile( + key: SettingsKeys.templates, + title: const Text(settingsTemplatesLabel), + subtitle: const Text(settingsTemplatesSecondary), + trailing: const CupertinoListTileChevron(), + onTap: onOpen, + ), + ], + ); + } + return Card( + margin: EdgeInsets.zero, + clipBehavior: Clip.antiAlias, + child: ListTile( + key: SettingsKeys.templates, + leading: const Icon(Icons.widgets_outlined), + title: const Text(settingsTemplatesLabel), + subtitle: const Text(settingsTemplatesSecondary), + trailing: const Icon(Icons.chevron_right), + onTap: onOpen, + ), + ); + } +} diff --git a/app/notes/T1-wire.md b/app/notes/T1-wire.md new file mode 100644 index 00000000..8b19cd62 --- /dev/null +++ b/app/notes/T1-wire.md @@ -0,0 +1,193 @@ +# T1-wire — register Templates in the real app + +## Result + +Templates is now a real app route and a Settings entry. `/templates` parses, +serialises and round-trips; unknown or malformed template paths still fall back +to `/pipelines`. The Settings screen has a `Templates` section with the web's +`Browse templates` row, which opens the landed `TemplatesScreen` in embedded +mode over the same `AppSession` gateway. Back — app bar, system Back and browser +Back — returns to the Settings screen instance that was already mounted, so its +fields, connection state and scroll offset survive. + +A create accepted by the existing prompt no longer leaves the Pipelines data +stale. The accepted `detail` advances one reload token, and the mounted +Pipelines destination re-reads through its controller. No row is inserted +optimistically: the row appears only from the server's fresh `list_pipelines` +reply. Showing Pipelines again adds no request. + +No fifth tab was added. `features/pipelines`, chat, runs, graph, artifacts, +attention and schedules were not edited. + +## Navigation shape + +Templates is a page in the app's existing `Navigator`, above the shell, exactly +like Search: + +- The shell route stays `/settings`, so the Settings destination is never + unmounted and its state is restored when the page closes. +- The Templates page owns the one visible native bar: `Templates` plus a + `Back to Settings` control (Material icon tooltip / Cupertino semantic label). + The embedded `TemplatesScreen` adds no second bar. +- `openTemplates` records `/templates`; `closeTemplates` (`Back to Settings`, + system Back via `popRoute`, or browser Back through `setNewRoutePath`) returns + to `/settings`. +- A direct `/templates` launch closes to `/settings` rather than a guessed + previous page. + +## Files + +New: + +| File | Lines | Responsibility | +| --- | ---: | --- | +| `lib/application/templates_destination.dart` | 122 | Templates page bar, shared-session connection states, embedded `TemplatesScreen`, accepted-detail forwarding | +| `lib/features/settings/settings_templates_section.dart` | 50 | Native `Templates` section row (`Browse templates` + server-catalogue line) | +| `test/application/templates_wiring_test.dart` | 344 | Embedded route, one-bar/one-socket, Back (bar + browser), Settings preservation, exactly-one create refresh, no optimistic row, standalone screen | +| `tool/templates_wiring_probe_entry.dart` | 26 | Real app composition with selectable Material/Cupertino host for the browser probe | +| `tool/templates_wiring_probe.mjs` | 713 | Isolated loopback websocket fixture + real headless-Chrome driver for both hosts | + +Modified: + +| File | Change | +| --- | --- | +| `lib/application/app_route.dart` | `templates` route kind/constant, `/templates` path, total parse branch (unknown detail paths stay Pipelines) | +| `lib/application/app_router.dart` | `templatesBuilder`, Templates page key, `openTemplates`/`closeTemplates`, system Back, page-removal close | +| `lib/application/pipelines_app.dart` | Templates builder over the shared session; `onCreated` advances a Pipelines reload token; Settings row callback; route→destination mapping | +| `lib/application/pipelines_destination.dart` | Optional `refreshToken`, composed with the connection epoch as the mounted screen's `syncToken` | +| `lib/features/settings/settings_screen.dart` | Optional `onOpenTemplates`; renders the section only when a route owner supplies it (no dead row standalone) | +| `lib/features/settings/settings_keys.dart` | `settings.templates` key | +| `test/application/app_route_test.dart` | `/templates` parse, slash normalisation, malformed detail fallback, round-trip | +| `test/application/app_router_test.dart` | open/close route, system Back, `/templates` boot close | + +The reload token is the sum of the connection epoch and the create counter. +Both only increase, so any reconnect or accepted create changes the value +without remounting `PipelinesScreen`; the selection and requested version are +preserved by the existing `syncToken` path. + +The Settings row uses the current web page's words exactly: the section heading +`Templates`, the row `Browse templates`, and the secondary line `Reusable +pipeline definitions offered by the server.` + +## Acceptance coverage + +- **Route**: `/templates` parses to `AppRoute.templates`, `/templates/` and a + full URL normalise, `/templates/release` and `/templates/a/b` fall back to + Pipelines, the serialiser round-trips every route, and `/templates` is the + serialised path. +- **Settings opens Templates**: tapping the row changes the URL to `/templates` + and shows the `TemplatesScreen` with `embedded: true`. +- **One bar / one socket**: exactly one visible `AppBar` (Material) or + `CupertinoNavigationBar` (Cupertino); no `Material` in the Cupertino host; the + client factory is called once; `list_templates` travels over that socket. +- **Back restores Settings**: the detail Back returns to the gallery; the page + Back returns to `/settings`, keeping the edited Server URL field; browser Back + from a second Templates visit does the same. Settings is not re-created (one + ping, no re-read). +- **Exactly one create refresh**: accepted `validate`/`submit` lead to exactly + one new `list_pipelines` and one new `list_runs`. Before the fresh reply, + `pipeline-row-41` is absent (no optimistic insert); after it, the row exists. + Switching to Pipelines adds no further request. +- **Standalone unchanged**: a non-embedded `TemplatesScreen` still owns its + `AppBar`; selecting a template shows the source and the bar's Back control. +- **Shared gateway**: the Templates destination reads `session.gateway`; no + screen or destination creates a client. + +## Checks actually run + +``` +cd app +flutter pub get # Got dependencies +dart format --output=none --set-exit-if-changed \ + lib/application lib/features/settings test/application \ + tool/templates_wiring_probe_entry.dart # 0 changed +flutter analyze # No issues found! +flutter test test/application/templates_wiring_test.dart # 4 passed +flutter test test/application test/features/settings \ + test/features/templates # 129 passed +flutter test # 952 passed +flutter build web -o /web-normal # ✓ Built +flutter build web --target=tool/templates_wiring_probe_entry.dart \ + -o /probe-web # ✓ Built +git diff --check # clean +``` + +## Browser evidence (real headless Chrome, loopback only) + +Both hosts run the real `PipelinesApp` composition from the probe entrypoint +against an isolated in-process websocket fixture. No production server, +database, operator session or real pipeline was contacted. The fixture records +the exact wire requests and exposes them at `/fixture/state`. + +Each host passed the same flow, seven checks each: Settings opens; the +`Browse templates` row opens `/templates` with one `list_templates` read; the +template detail shows metadata and the verbatim source; opening a template +sends no write; Create sends exactly one `validate` and one `submit` with +`create_only: true` and the verbatim source; the accepted detail causes exactly +one fresh `list_pipelines`; detail Back → gallery → `Back to Settings` restores +the same Settings screen (`ping` unchanged); Pipelines then shows the new +server row with exactly two `list_pipelines`/`list_runs` reads and one socket. + +Material dark, 390×844 (`public/t1-wire-material/`): +`t1-wire-material-pipelines.png`, `-settings.png`, `-gallery.png`, `-detail.png`, +`-created.png`, `-back-settings.png`, `-refreshed-pipelines.png`. + +Cupertino dark, 390×844 (`public/t1-wire-cupertino/`): the same seven captures +with the `t1-wire-cupertino-` prefix. + +Inspected captures: the Material Templates bar + gallery + detail; the Material +create dialog with `Created "Probe release". It is in the Pipelines list.`; the +returned Settings screen scrolled to the `Templates` section with +`Browse templates`; the refreshed Pipelines list showing `Probe release`. The +Cupertino bar, gallery, detail with `Back Templates`, created dialog, returned +Settings and refreshed list were inspected too. The returned Settings captures +show the retained scroll offset, matching the widget test's retained field text. + +## Task diff + +``` + M app/lib/application/app_route.dart + M app/lib/application/app_router.dart + M app/lib/application/pipelines_app.dart + M app/lib/application/pipelines_destination.dart + M app/lib/features/settings/settings_keys.dart + M app/lib/features/settings/settings_screen.dart + M app/test/application/app_route_test.dart + M app/test/application/app_router_test.dart +?? app/lib/application/templates_destination.dart +?? app/lib/features/settings/settings_templates_section.dart +?? app/test/application/templates_wiring_test.dart +?? app/tool/templates_wiring_probe.mjs +?? app/tool/templates_wiring_probe_entry.dart +?? app/notes/T1-wire.md +``` + +No tracked file outside `app/` was touched; no other lane's files changed. The +only file outside the stated own list is `application/pipelines_destination.dart` +(the optional reload token seam), needed to re-read through the mounted +Pipelines controller rather than remounting it or inserting a row. + +## Honest limits + +- **Not committed.** The stage instruction says not to commit, push or deploy, + so the candidate above remains uncommitted even though the run prompt asks to + commit a reviewed candidate. Nothing was staged, pushed or deployed. +- The browser fixture is an isolated fake of the protocol, not the live server. + No real template create happened; no operator data or real pipeline changed. +- Mobile (Android/iOS) is unverified: no Android/iOS build, emulator, device or + ADB. Cupertino captures are Chrome's rendering of the Cupertino widgets. +- Templates detail selection is local state, not `/templates/:key`; the task + scoped the route to the gallery, and a deep-linked detail path falls back to + Pipelines rather than inventing a selection. +- `/settings/templates` is not parsed as an alias; the web has that alias, but + this slice registers only the requested `/templates` route. +- Stage counts/graphs in the gallery remain unimplemented from the existing + gallery slice; this task did not add per-card `validate` calls. + +## Manager completion after the server evidence failure + +The run ended with the server's re-saved-visit evidence bug (fixed and redeployed +separately). The retained tree is complete: 91 application/settings tests pass. +Manager merged it directly. Templates is reachable from Settings without adding a +tab, Back restores the same Settings screen, and an accepted create only +invalidates the Pipelines list so the next server reply supplies the new row. diff --git a/app/test/application/app_route_test.dart b/app/test/application/app_route_test.dart index cdd2aeee..47171c65 100644 --- a/app/test/application/app_route_test.dart +++ b/app/test/application/app_route_test.dart @@ -13,11 +13,13 @@ void main() { ); expect(AppRoute.parse('/search'), AppRoute.search); expect(AppRoute.parse('/settings'), AppRoute.settings); + expect(AppRoute.parse('/templates'), AppRoute.templates); }); test('normalises slashes and accepts a full URL, query and fragment', () { expect(AppRoute.parse('/runs/'), AppRoute.runs); expect(AppRoute.parse('/pipelines///'), AppRoute.pipelines); + expect(AppRoute.parse('/templates/'), AppRoute.templates); expect( AppRoute.parse('http://127.0.0.1:8096/runs/7?action=decide#top'), AppRoute.run(7), @@ -43,6 +45,7 @@ void main() { '/runs/1/extra', '/pipelines/2', '/search/1', + '/templates/release', '/chat/a/b', '/chat/%2F', '/chat/${'x' * 201}', @@ -62,11 +65,13 @@ void main() { AppRoute.chatSession('probe_open-1'), AppRoute.search, AppRoute.settings, + AppRoute.templates, ]) { expect(AppRoute.parse(route.path), route); } expect(AppRoute.run(3).path, '/runs/3'); expect(AppRoute.chatSession('probe_open-1').path, '/chat/probe_open-1'); expect(AppRoute.chatSession('bad id').path, '/chat'); + expect(AppRoute.templates.path, '/templates'); }); } diff --git a/app/test/application/app_router_test.dart b/app/test/application/app_router_test.dart index e713f173..1c5c3731 100644 --- a/app/test/application/app_router_test.dart +++ b/app/test/application/app_router_test.dart @@ -28,4 +28,25 @@ void main() { expect(await router.popRoute(), isFalse); }); + + test('Templates opens above Settings and Back restores the route', () async { + final router = delegate(AppRoute.settings); + addTearDown(router.dispose); + + router.openTemplates(); + expect(router.route, AppRoute.templates); + expect(router.templatesOpen, isTrue); + + expect(await router.popRoute(), isTrue); + expect(router.route, AppRoute.settings); + expect(router.templatesOpen, isFalse); + }); + + test('a /templates boot link still closes back to Settings', () async { + final router = delegate(AppRoute.templates); + addTearDown(router.dispose); + + router.closeTemplates(); + expect(router.route, AppRoute.settings); + }); } diff --git a/app/test/application/templates_wiring_test.dart b/app/test/application/templates_wiring_test.dart new file mode 100644 index 00000000..f194c4ca --- /dev/null +++ b/app/test/application/templates_wiring_test.dart @@ -0,0 +1,344 @@ +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/application/templates_destination.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/settings/settings_keys.dart'; +import 'package:pipelines_app/features/templates/screen.dart'; +import 'package:pipelines_app/features/templates/ui/template_create_wording.dart'; +import 'package:pipelines_app/features/templates/ui/template_detail.dart' + show templateDetailBackKey; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; +import '../features/pipelines/fixtures.dart'; +import '../features/templates/ui/template_gallery_test_support.dart' + show GalleryGateway, galleryTemplates, pumpGallery, templatesReply; +import 'pipelines_app_test.dart' show webServer; +import 'pipelines_replies.dart'; + +List> requestsOf(FakeChannel channel, String type) => + channel.outgoing + .map((frame) => jsonDecode(frame as String) as Map) + .where((frame) => frame['type'] == type) + .toList(); + +Future>> waitForCount( + WidgetTester tester, + FakeChannel channel, + String type, + int count, +) async { + for ( + var attempt = 0; + attempt < 100 && requestsOf(channel, type).length < count; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 10)); + } + final requests = requestsOf(channel, type); + expect( + requests.length, + greaterThanOrEqualTo(count), + reason: 'Timed out waiting for $type #$count', + ); + return requests; +} + +Future reply( + WidgetTester tester, + FakeChannel channel, + String type, + int count, + Map body, +) async { + final requests = await waitForCount(tester, channel, type, count); + channel.incoming.add(jsonEncode({'id': requests[count - 1]['id'], ...body})); + await tester.pump(); + await tester.pump(); +} + +Future pumpApp( + WidgetTester tester, { + required FakeChannel channel, + required PipelinesClient client, + required PlatformRouteInformationProvider provider, + required bool cupertino, +}) async { + tester.view.physicalSize = const Size(1100, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + if (cupertino) { + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + } + SharedPreferences.setMockInitialValues({}); + await tester.pumpWidget( + PipelinesApp( + server: webServer(), + client: client, + cupertino: cupertino, + routeInformationProvider: provider, + ), + ); + await tester.pump(); +} + +Future openSettings( + WidgetTester tester, + FakeChannel channel, + PlatformRouteInformationProvider provider, +) async { + await tester.tap(find.text('Settings').last); + await tester.pump(); + await tester.pump(); + expect(provider.value.uri.path, '/settings'); + // Settings pings the shared socket; answer it so later reads are not queued. + await reply(tester, channel, 'ping', 1, { + 'type': 'pong', + 'build': {'version': 'probe'}, + 'time': 'fixture', + }); +} + +Future openTemplates( + WidgetTester tester, + FakeChannel channel, + PlatformRouteInformationProvider provider, { + int listRead = 1, +}) async { + await tester.ensureVisible(find.byKey(SettingsKeys.templates)); + await tester.tap(find.byKey(SettingsKeys.templates)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 600)); + expect(provider.value.uri.path, '/templates'); + await reply(tester, channel, 'list_templates', listRead, { + 'type': 'templates', + 'templates': [ + { + 'key': 'release', + 'name': 'Release workflow', + 'description': 'Ship a version', + 'source': 'name: "release"\n', + 'scheduled': true, + }, + ], + }); +} + +void main() { + testWidgets('non-embedded TemplatesScreen keeps its own native bar', ( + tester, + ) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + await pumpGallery(tester, gateway); + + expect(find.byType(AppBar), findsOneWidget); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pump(); + expect(find.text('Definition source'), findsOneWidget); + expect(find.byKey(templatesBackKey), findsOneWidget); + expect(gateway.callsOf('list_templates'), hasLength(1)); + }); + + for (final cupertino in [false, true]) { + testWidgets( + 'Settings opens the embedded Templates page and Back restores it ' + '($cupertino)', + (tester) async { + final fixture = PipelineFixture(); + final channel = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) { + sockets++; + return channel; + }, + ); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation( + uri: Uri.parse('/pipelines'), + ), + ); + addTearDown(provider.dispose); + + await pumpApp( + tester, + channel: channel, + client: client, + provider: provider, + cupertino: cupertino, + ); + await replyPipelines(tester, channel, fixture); + + await openSettings(tester, channel, provider); + // An edit that only Settings owns must survive the Templates detour. + await tester.enterText(find.byType(EditableText).first, 'edited url'); + await tester.pump(); + expect(find.text('edited url'), findsOneWidget); + + await openTemplates(tester, channel, provider); + final screen = tester.widget( + find.byType(TemplatesScreen), + ); + expect(screen.embedded, isTrue); + expect(find.text('Release workflow'), findsOneWidget); + // One visible navigation bar: the Templates page owns it, the shell is + // preserved underneath. + expect( + find.byType(cupertino ? CupertinoNavigationBar : AppBar), + findsOneWidget, + ); + if (cupertino) { + expect(find.byType(Material), findsNothing); + } + expect(sockets, 1); + expect(requestsOf(channel, 'list_templates'), hasLength(1)); + + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pump(); + expect(find.text('Definition source'), findsOneWidget); + + // Detail Back returns to the gallery, then the page Back restores the + // same Settings state. + await tester.tap(find.byKey(templateDetailBackKey)); + await tester.pump(); + await tester.tap(find.byKey(templatesPageBackKey)); + await tester.pumpAndSettle(); + + expect(provider.value.uri.path, '/settings'); + expect(find.byType(TemplatesScreen), findsNothing); + expect(find.text('edited url'), findsOneWidget); + expect(find.text('Server URL'), findsOneWidget); + expect(sockets, 1); + expect(requestsOf(channel, 'ping'), hasLength(1)); + + // Browser Back from /templates follows the same close path. + await openTemplates(tester, channel, provider, listRead: 2); + expect(find.byType(TemplatesScreen), findsOneWidget); + await provider.didPushRouteInformation( + RouteInformation(uri: Uri.parse('/settings')), + ); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/settings'); + expect(find.byType(TemplatesScreen), findsNothing); + expect(find.text('edited url'), findsOneWidget); + expect(requestsOf(channel, 'list_templates'), hasLength(2)); + expect(sockets, 1); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }, + ); + } + + testWidgets('an accepted create re-reads Pipelines exactly once', ( + tester, + ) async { + final fixture = PipelineFixture(); + final channel = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) { + sockets++; + return channel; + }, + ); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')), + ); + addTearDown(provider.dispose); + + await pumpApp( + tester, + channel: channel, + client: client, + provider: provider, + cupertino: false, + ); + await replyPipelines(tester, channel, fixture); + expect( + find.byKey(const Key('pipeline-row-41'), skipOffstage: false), + findsNothing, + ); + + await openSettings(tester, channel, provider); + await openTemplates(tester, channel, provider); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pump(); + await tester.tap(find.byKey(templateCreateActionKey)); + await tester.pump(); + await tester.enterText(find.byKey(templateCreateNameKey), 'Probe release'); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pump(); + + await reply(tester, channel, 'validate', 1, { + 'type': 'graph', + 'graph': {'stages': []}, + }); + await reply(tester, channel, 'submit', 1, { + 'type': 'pipeline', + 'detail': {'id': 41, 'name': 'Probe release'}, + }); + expect( + find.text('Created "Probe release". It is in the Pipelines list.'), + findsOneWidget, + ); + + // The detail itself never adds a row: the hidden list is still the old one + // until the fresh server reply arrives. + final refreshes = await waitForCount(tester, channel, 'list_pipelines', 2); + expect( + find.byKey(const Key('pipeline-row-41'), skipOffstage: false), + findsNothing, + ); + channel.incoming.add( + jsonEncode({ + 'id': refreshes[1]['id'], + 'type': 'pipelines', + 'pipelines': [ + ...fixture.summaries, + pipelineSummary(id: 41, name: 'Probe release'), + ], + }), + ); + await tester.pump(); + await reply(tester, channel, 'list_runs', 2, { + 'type': 'runs', + 'runs': fixture.runs, + }); + expect( + find.byKey(const Key('pipeline-row-41'), skipOffstage: false), + findsOneWidget, + ); + + await tester.tap(find.byKey(templateCreateCancelKey)); + await tester.pump(); + await tester.tap(find.byKey(templateDetailBackKey)); + await tester.pump(); + await tester.tap(find.byKey(templatesPageBackKey)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Pipelines').last); + await tester.pumpAndSettle(); + + expect(provider.value.uri.path, '/pipelines'); + expect(find.text('Probe release'), findsOneWidget); + // Only the accepted detail's invalidation re-read the list; showing it + // again adds no request. + expect(requestsOf(channel, 'list_pipelines'), hasLength(2)); + expect(requestsOf(channel, 'list_runs'), hasLength(2)); + expect(requestsOf(channel, 'validate'), hasLength(1)); + expect(requestsOf(channel, 'submit'), hasLength(1)); + expect(sockets, 1); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }); +} diff --git a/app/tool/templates_wiring_probe.mjs b/app/tool/templates_wiring_probe.mjs new file mode 100644 index 00000000..a380cf9d --- /dev/null +++ b/app/tool/templates_wiring_probe.mjs @@ -0,0 +1,713 @@ +// Real-browser acceptance for the registered Templates destination. +// +// From app/: +// flutter build web -o build/templates_wiring_web +// OPENCODE_ARTIFACT_DIR= \ +// node tool/templates_wiring_probe.mjs build/templates_wiring_web +// +// PROBE_HOST (material|cupertino) selects the host. The fixture server is an +// isolated loopback implementation of the Pipelines websocket protocol used by +// this flow; no production server, database or operator data is involved. +import { createServer } from 'node:http'; +import { readFile, mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { createHash } from 'node:crypto'; + +const root = resolve(process.argv[2] ?? 'build/templates_wiring_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 host = process.env.PROBE_HOST === 'cupertino' ? 'cupertino' : 'material'; +const width = Number(process.env.PROBE_WIDTH ?? 390); +const height = Number(process.env.PROBE_HEIGHT ?? 844); +const deviceScaleFactor = Number(process.env.PROBE_DPR ?? 1); +const capturePrefix = process.env.PROBE_CAPTURE_PREFIX ?? `t1-wire-${host}`; + +const MIME = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', +}; + +const PIPELINES = [ + { + id: 1, name: 'Alpha review', version: 2, stages: 2, + created_at: '2026-10-21T09:00:00', updated_at: '2026-10-21T10:00:00', + scheduled: true, schedule_count: 1, enabled_schedule_count: 1, + }, + { + id: 2, name: 'Beta deploy', version: 1, stages: 1, + created_at: '2026-10-20T09:00:00', updated_at: '2026-10-20T10:00:00', + scheduled: false, schedule_count: 0, enabled_schedule_count: 0, + }, +]; +const RUNS = [ + { + id: 42, pipeline_id: 1, status: 'succeeded', + created_at: '2026-10-21T09:30:00', finished_at: '2026-10-21T09:35:00', + executing: false, + }, +]; +const TEMPLATE = { + key: 'release', + name: 'Release workflow', + description: 'Ship a version', + source: 'name: "release"\nstages:\n build:\n type: model\n', + scheduled: true, +}; + +function accept(key) { + return createHash('sha1') + .update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`) + .digest('base64'); +} + +function frame(opcode, payload) { + const length = payload.length; + let header; + if (length < 126) { + header = Buffer.from([0x80 | opcode, length]); + } else if (length < 65536) { + header = Buffer.alloc(4); + header[0] = 0x80 | opcode; + header[1] = 126; + header.writeUInt16BE(length, 2); + } else { + header = Buffer.alloc(10); + header[0] = 0x80 | opcode; + header[1] = 127; + header.writeBigUInt64BE(BigInt(length), 2); + } + return Buffer.concat([header, payload]); +} + +class Connection { + constructor(socket, owner) { + this.socket = socket; + this.owner = owner; + this.buffer = Buffer.alloc(0); + this.fragments = []; + this.fragmentOpcode = 0; + } + + push(chunk) { + if (chunk?.length) this.buffer = Buffer.concat([this.buffer, chunk]); + this.parse(); + } + + parse() { + while (this.buffer.length >= 2) { + const first = this.buffer[0]; + const second = this.buffer[1]; + const fin = (first & 0x80) !== 0; + const opcode = first & 0x0f; + const masked = (second & 0x80) !== 0; + let length = second & 0x7f; + let offset = 2; + if (length === 126) { + if (this.buffer.length < 4) return; + length = this.buffer.readUInt16BE(2); + offset = 4; + } else if (length === 127) { + if (this.buffer.length < 10) return; + const big = this.buffer.readBigUInt64BE(2); + if (big > BigInt(Number.MAX_SAFE_INTEGER)) return this.close(); + length = Number(big); + offset = 10; + } + const maskOffset = offset; + if (masked) { + if (this.buffer.length < offset + 4) return; + offset += 4; + } + if (this.buffer.length < offset + length) return; + let payload = Buffer.from(this.buffer.subarray(offset, offset + length)); + if (masked) { + const mask = this.buffer.subarray(maskOffset, maskOffset + 4); + for (let index = 0; index < payload.length; index++) { + payload[index] ^= mask[index % 4]; + } + } + this.buffer = this.buffer.subarray(offset + length); + this.handleFrame(fin, opcode, payload); + } + } + + handleFrame(fin, opcode, payload) { + if (opcode === 0x8) return this.close(); + if (opcode === 0x9) return void this.socket.write(frame(0x0a, payload)); + if (opcode === 0x0a) return; + if (opcode === 0x0) { + this.fragments.push(payload); + if (fin) { + const data = Buffer.concat(this.fragments); + this.fragments = []; + this.message(this.fragmentOpcode, data); + } + return; + } + if (opcode !== 0x1) return; + if (!fin) { + this.fragmentOpcode = opcode; + this.fragments = [payload]; + return; + } + this.message(opcode, payload); + } + + message(_opcode, payload) { + let request; + try { + request = JSON.parse(payload.toString('utf8')); + } catch { + return; + } + this.owner.onMessage(this, request); + } + + send(value) { + if (this.socket.destroyed) return; + this.socket.write(frame(0x1, Buffer.from(JSON.stringify(value)))); + } + + close() { + if (!this.socket.destroyed) this.socket.end(); + } +} + +async function staticFile(base, pathname, req, res) { + let file = resolve(base, `.${pathname}`); + if (file !== base && !file.startsWith(base + sep)) { + res.writeHead(403).end(); + return; + } + try { + if ((await stat(file)).isDirectory()) file = join(file, 'index.html'); + } catch { + if (extname(pathname)) { + res.writeHead(404).end('not found'); + return; + } + file = join(base, 'index.html'); + } + try { + const body = await readFile(file); + res + .writeHead(200, { + 'content-type': MIME[extname(file)] ?? 'application/octet-stream', + 'cache-control': 'no-store', + }) + .end(req.method === 'HEAD' ? undefined : body); + } catch { + res.writeHead(404).end('not found'); + } +} + +async function startFixture(base) { + const connections = new Set(); + const sockets = new Set(); + const state = { + connections: 0, + subscribed: 0, + ping: 0, + listPipelines: 0, + listRuns: 0, + listTemplates: 0, + validates: 0, + submits: 0, + submitsBody: [], + }; + const created = []; + const pipelines = () => [ + ...PIPELINES, + ...created.map((item) => ({ + id: item.id, + name: item.name, + version: 1, + stages: 1, + created_at: '2026-10-22T00:00:00', + updated_at: '2026-10-22T00:00:00', + scheduled: false, + schedule_count: 0, + enabled_schedule_count: 0, + })), + ]; + + const server = createServer(async (req, res) => { + const pathname = new URL(req.url, 'http://fixture').pathname; + if (pathname === '/fixture/state') { + res + .writeHead(200, { 'content-type': 'application/json' }) + .end(JSON.stringify({ ...state, pipelines: pipelines().length })); + return; + } + if (req.method !== 'GET' && req.method !== 'HEAD') { + res.writeHead(405).end(); + return; + } + await staticFile(base, pathname, req, res); + }); + + server.on('upgrade', (req, socket, head) => { + const url = new URL(req.url, 'http://fixture'); + if ( + url.pathname !== '/connect' || + req.headers.upgrade?.toLowerCase() !== 'websocket' || + !req.headers['sec-websocket-key'] + ) { + socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n'); + return; + } + socket.write( + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + `Sec-WebSocket-Accept: ${accept(req.headers['sec-websocket-key'])}\r\n\r\n`, + ); + const connection = new Connection(socket, { + onMessage: (client, request) => { + if (request.type === 'subscribe') { + // Like the real server in this app's probes, the watch stays silent. + state.subscribed++; + return; + } + if (request.type === 'unsubscribe') return; + if (request.type === 'ping') { + state.ping++; + client.send({ + id: request.id, + type: 'pong', + build: { version: 'fixture templates build' }, + time: '2026-10-22T00:00:00Z', + }); + return; + } + if (request.type === 'list_pipelines') { + state.listPipelines++; + client.send({ id: request.id, type: 'pipelines', pipelines: pipelines() }); + return; + } + if (request.type === 'list_runs') { + state.listRuns++; + client.send({ id: request.id, type: 'runs', runs: RUNS }); + return; + } + if (request.type === 'list_templates') { + state.listTemplates++; + client.send({ id: request.id, type: 'templates', templates: [TEMPLATE] }); + return; + } + if (request.type === 'validate') { + state.validates++; + client.send({ id: request.id, type: 'graph', graph: { stages: [] } }); + return; + } + if (request.type === 'submit') { + state.submits++; + state.submitsBody.push({ + name: request.name, + source: request.source, + create_only: request.create_only, + }); + const id = 41 + created.length; + const name = String(request.name ?? '').trim() || 'Unnamed'; + created.push({ id, name, source: request.source }); + client.send({ + id: request.id, + type: 'pipeline', + detail: { id, name }, + }); + return; + } + client.send({ + id: request.id, + type: 'error', + error: `Fixture does not implement ${request.type}`, + }); + }, + }); + connections.add(connection); + state.connections = connections.size; + socket.on('data', (chunk) => connection.push(chunk)); + socket.on('close', () => { + connections.delete(connection); + state.connections = connections.size; + }); + socket.on('error', () => connections.delete(connection)); + connection.push(head); + }); + + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + server.on('connection', (socket) => { + sockets.add(socket); + socket.on('close', () => sockets.delete(socket)); + }); + const port = server.address().port; + return { + server, + origin: `http://127.0.0.1:${port}`, + created, + close: () => + new Promise((resolveClose) => { + for (const connection of connections) connection.close(); + server.close(() => resolveClose()); + for (const socket of sockets) socket.destroy(); + }), + }; +} + +const fixture = await startFixture(await realpathOrSelf(root)); +const profile = await mkdtemp(join(tmpdir(), 'templates-wiring-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; +}); + +function realpathOrSelf(path) { + return resolve(path); +} + +async function waitFor(check, label, attempts = 180) { + 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(JSON.stringify(response)); + if (response.result?.exceptionDetails) { + throw new Error(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 pathname = () => evaluate('location.pathname'); + const assertPath = async (path) => { + await waitFor(async () => (await pathname()) === path, `path ${path}`); + }; + + const labelPoint = (label, contains) => + 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 }; + })()`); + + const wheel = async (deltaY) => { + await send( + 'Input.dispatchMouseEvent', + { + type: 'mouseWheel', + x: width / 2, + y: height / 2, + deltaX: 0, + deltaY, + }, + session, + ); + await delay(250); + }; + + const clickLabel = async (label, { contains = false } = {}) => { + for (let attempt = 0; attempt < 12; attempt++) { + const point = await labelPoint(label, contains); + if (point && point.y > 4 && point.y < height - 4) { + 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(500); + return; + } + // The Settings page scrolls; bring an off-screen row into the viewport. + await wheel(point && point.y < 0 ? -350 : 350); + } + throw new Error( + `Could not click ${JSON.stringify(label)}. Labels: ${JSON.stringify(await labels())}`, + ); + }; + + const typeIntoFocused = async (value) => { + const focused = await evaluate(`(() => { + const inputs = [...document.querySelectorAll('input, textarea')].filter((el) => { + const r = el.getBoundingClientRect(); + return r.width > 0 && r.height > 0; + }); + const input = inputs[inputs.length - 1]; + if (!input) return false; + input.focus(); + input.select?.(); + input.setSelectionRange?.(0, (input.value || '').length); + return true; + })()`); + if (!focused) throw new Error('No semantics input was available to type into'); + await delay(300); + await send('Input.insertText', { text: value }, session); + await delay(400); + }; + + const state = () => + evaluate(`fetch('${fixture.origin}/fixture/state').then((r) => r.json())`); + 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: `${fixture.origin}/?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('Alpha review'); + captures.push(await capture(`${capturePrefix}-pipelines`)); + + await clickLabel('Settings'); + await assertPath('/settings'); + await assertBody('Server URL'); + await assertBody('Browse templates'); + const settingsState = await state(); + captures.push(await capture(`${capturePrefix}-settings`)); + + await clickLabel('Browse templates', { contains: true }); + await assertPath('/templates'); + await assertBody('Release workflow'); + const opened = await state(); + if (opened.listTemplates !== 1) { + throw new Error(`Templates did not read the catalogue once: ${JSON.stringify(opened)}`); + } + captures.push(await capture(`${capturePrefix}-gallery`)); + + await clickLabel('Release workflow', { contains: true }); + await assertBody('Definition source'); + 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`)); + + await clickLabel('Create pipeline from this template'); + await assertBody('Create from Release workflow'); + await typeIntoFocused('Probe release'); + await clickLabel('Create'); + await assertBody('Created "Probe release". It is in the Pipelines list.'); + const createdState = await state(); + if ( + createdState.validates !== 1 || + createdState.submits !== 1 || + createdState.submitsBody?.[0]?.create_only !== true || + createdState.submitsBody?.[0]?.source !== TEMPLATE.source + ) { + throw new Error(`The accepted create drifted: ${JSON.stringify(createdState)}`); + } + if (createdState.listPipelines !== 2) { + throw new Error( + `The accepted detail did not request exactly one fresh list: ${JSON.stringify(createdState)}`, + ); + } + captures.push(await capture(`${capturePrefix}-created`)); + checks.push({ check: 'created detail triggered one fresh list read', state: createdState }); + + await clickLabel('Close'); + await assertBody('Definition source'); + + // Detail Back returns to the gallery; the page Back restores Settings. + await clickLabel(host === 'cupertino' ? 'Back Templates' : 'Back'); + await assertBody('Release workflow'); + await clickLabel('Back to Settings'); + await assertPath('/settings'); + await assertBody('Server URL'); + await assertBody('Browse templates'); + captures.push(await capture(`${capturePrefix}-back-settings`)); + const restored = await state(); + if (restored.listTemplates !== 1 || restored.submits !== 1) { + throw new Error(`Returning to Settings re-read or re-submitted: ${JSON.stringify(restored)}`); + } + if (restored.ping !== settingsState.ping) { + throw new Error(`Settings was remounted instead of preserved: ${JSON.stringify(restored)}`); + } + checks.push({ check: 'Back restored the same Settings screen', state: restored }); + + await clickLabel('Pipelines'); + await assertPath('/pipelines'); + await assertBody('Probe release'); + const refreshed = await state(); + if (refreshed.listPipelines !== 2 || refreshed.listRuns !== 2) { + throw new Error(`Showing Pipelines added a read: ${JSON.stringify(refreshed)}`); + } + if (refreshed.connections !== 1) { + throw new Error(`Templates opened a second socket: ${JSON.stringify(refreshed)}`); + } + captures.push(await capture(`${capturePrefix}-refreshed-pipelines`)); + checks.push({ check: 'Pipelines showed the server row over one socket', state: refreshed }); + + console.log( + JSON.stringify( + { + ok: true, + origin: fixture.origin, + host, + viewport: { width, height, deviceScaleFactor }, + checks, + captures, + }, + null, + 2, + ), + ); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + await fixture.close(); + await rm(profile, { recursive: true, force: true }); +} diff --git a/app/tool/templates_wiring_probe_entry.dart b/app/tool/templates_wiring_probe_entry.dart new file mode 100644 index 00000000..b9c60548 --- /dev/null +++ b/app/tool/templates_wiring_probe_entry.dart @@ -0,0 +1,26 @@ +import 'package:flutter/widgets.dart'; +import 'package:pipelines_app/application/app_url_strategy.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; + +/// Browser acceptance entrypoint for the registered Templates destination. +/// +/// It is the real application composition (the same router, shell, Settings and +/// Pipelines destinations); only the host style is selectable so both Material +/// and Cupertino can be exercised on the web. `?host=material|cupertino` picks +/// the host. Every request is answered by the isolated loopback fixture in +/// `tool/templates_wiring_probe.mjs`; no production server is contacted. +void main() { + useAppUrlStrategy(); + final host = Uri.base.queryParameters['host']; + runApp( + PipelinesApp( + server: ServerEndpoint.resolve(base: Uri.base, web: true), + cupertino: switch (host) { + 'cupertino' => true, + 'material' => false, + _ => null, + }, + ), + ); +}