From 35a8aab77233c739f53be9574f8ce07a76fa0977 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 17:26:36 +0100 Subject: [PATCH] feat(app): compose live Runs with deep links and reconnect retention --- app/lib/application/app.dart | 79 ++++ app/lib/application/app_route.dart | 96 ++++ app/lib/application/app_router.dart | 106 +++++ app/lib/application/app_session.dart | 168 +++++++ app/lib/application/app_url_strategy.dart | 10 + .../application/app_url_strategy_stub.dart | 1 + app/lib/application/app_url_strategy_web.dart | 3 + app/lib/application/bootstrap.dart | 20 + app/lib/application/pipelines_app.dart | 129 ++++++ app/lib/application/runs_destination.dart | 249 +++++++++++ app/lib/application/server_endpoint.dart | 65 +++ app/lib/features/runs/domain/run_models.dart | 22 +- app/lib/features/runs/screen.dart | 113 +++-- .../runs/ui/run_detail_cupertino.dart | 2 +- .../features/runs/ui/run_detail_material.dart | 2 +- app/lib/features/runs/ui/run_detail_view.dart | 39 +- app/lib/features/runs/ui/runs_controller.dart | 10 + app/lib/features/runs/ui/runs_list.dart | 18 +- app/lib/main.dart | 39 +- app/lib/shell/adaptive_shell.dart | 32 +- app/lib/ui/adaptive/host.dart | 10 + app/notes/I1.md | 119 +++++ app/pubspec.lock | 2 +- app/pubspec.yaml | 2 + app/test/application/app_route_test.dart | 52 +++ app/test/application/app_session_test.dart | 148 ++++++ app/test/application/pipelines_app_test.dart | 177 ++++++++ .../application/runs_destination_test.dart | 302 +++++++++++++ .../application/server_endpoint_test.dart | 61 +++ .../runs/ui/run_detail_widget_test.dart | 2 +- .../features/runs/ui/runs_screen_test.dart | 247 ++++++++++ app/tool/runs_probe.mjs | 423 ++++++++++++++++++ app/tool/runs_probe_entry.dart | 8 + app/tool/runs_probe_server.mjs | 410 +++++++++++++++++ 34 files changed, 3038 insertions(+), 128 deletions(-) create mode 100644 app/lib/application/app.dart create mode 100644 app/lib/application/app_route.dart create mode 100644 app/lib/application/app_router.dart create mode 100644 app/lib/application/app_session.dart create mode 100644 app/lib/application/app_url_strategy.dart create mode 100644 app/lib/application/app_url_strategy_stub.dart create mode 100644 app/lib/application/app_url_strategy_web.dart create mode 100644 app/lib/application/bootstrap.dart create mode 100644 app/lib/application/pipelines_app.dart create mode 100644 app/lib/application/runs_destination.dart create mode 100644 app/lib/application/server_endpoint.dart create mode 100644 app/lib/ui/adaptive/host.dart create mode 100644 app/notes/I1.md create mode 100644 app/test/application/app_route_test.dart create mode 100644 app/test/application/app_session_test.dart create mode 100644 app/test/application/pipelines_app_test.dart create mode 100644 app/test/application/runs_destination_test.dart create mode 100644 app/test/application/server_endpoint_test.dart create mode 100644 app/test/features/runs/ui/runs_screen_test.dart create mode 100644 app/tool/runs_probe.mjs create mode 100644 app/tool/runs_probe_entry.dart create mode 100644 app/tool/runs_probe_server.mjs diff --git a/app/lib/application/app.dart b/app/lib/application/app.dart new file mode 100644 index 00000000..311a4a8c --- /dev/null +++ b/app/lib/application/app.dart @@ -0,0 +1,79 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../shell/adaptive_shell.dart'; +import '../shell/destination.dart'; + +/// The injectable application shell. Composition supplies the live feature +/// bodies and, when it owns a route, the selected destination; widget tests +/// can continue to pass a small map or no bodies at all. +class MyApp extends StatelessWidget { + const MyApp({ + super.key, + this.destinationBodies = const {}, + this.cupertino, + this.destination, + this.onDestinationSelected, + }) : routerConfig = null; + + /// A host for a [Router]-owned location, so browser Back/Forward and deep + /// links use Flutter's multi-entry web history instead of a second, competing + /// history implementation. + const MyApp.router({ + super.key, + required RouterConfig this.routerConfig, + this.cupertino, + }) : destinationBodies = const {}, + destination = null, + onDestinationSelected = null; + + final Map destinationBodies; + final bool? cupertino; + final AppDestination? destination; + final ValueChanged? onDestinationSelected; + final RouterConfig? routerConfig; + + @override + Widget build(BuildContext context) { + final router = routerConfig; + if (cupertino ?? _platformIsCupertino) { + if (router != null) { + return CupertinoApp.router(title: 'Pipelines', routerConfig: router); + } + return CupertinoApp( + title: 'Pipelines', + home: AdaptiveShell( + destinationBodies: destinationBodies, + cupertino: true, + destination: destination, + onDestinationSelected: onDestinationSelected, + ), + ); + } + if (router != null) { + return MaterialApp.router( + title: 'Pipelines', + theme: ThemeData(), + darkTheme: ThemeData(brightness: Brightness.dark), + themeMode: ThemeMode.system, + routerConfig: router, + ); + } + return MaterialApp( + title: 'Pipelines', + theme: ThemeData(), + darkTheme: ThemeData(brightness: Brightness.dark), + themeMode: ThemeMode.system, + home: AdaptiveShell( + destinationBodies: destinationBodies, + destination: destination, + onDestinationSelected: onDestinationSelected, + ), + ); + } + + bool get _platformIsCupertino => + defaultTargetPlatform == TargetPlatform.iOS || + defaultTargetPlatform == TargetPlatform.macOS; +} diff --git a/app/lib/application/app_route.dart b/app/lib/application/app_route.dart new file mode 100644 index 00000000..889f04f5 --- /dev/null +++ b/app/lib/application/app_route.dart @@ -0,0 +1,96 @@ +/// The destinations the app has a URL for. +/// +/// 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, settings } + +/// One page route: a destination plus the run it opens, if any. +/// +/// Parsing is total, like the web client's route model: an unknown or +/// malformed path resolves to the default Pipelines list instead of throwing. +/// The serialiser is its inverse for every route the app can produce. +class AppRoute { + const AppRoute(this.kind, {this.runId}); + + static const pipelines = AppRoute(AppRouteKind.pipelines); + static const runs = AppRoute(AppRouteKind.runs); + static const chat = AppRoute(AppRouteKind.chat); + static const settings = AppRoute(AppRouteKind.settings); + + static const run = _RunRouteFactory(); + + final AppRouteKind kind; + + /// The run shown by the Runs destination, or null for the list. + final int? runId; + + /// The path the app writes into history for this route. + String get path => switch (kind) { + AppRouteKind.pipelines => '/pipelines', + AppRouteKind.runs => runId == null ? '/runs' : '/runs/$runId', + AppRouteKind.chat => '/chat', + AppRouteKind.settings => '/settings', + }; + + /// Parses a browser pathname (or a full URL) into a route. + /// + /// `/runs/abc` and other malformed details are the default route, matching + /// the web parser; `/pipelines/` and other trailing slashes are normalised. + static AppRoute parse(String location) { + var path = location.trim(); + if (path.isEmpty) return pipelines; + if (path.contains('://')) { + final uri = Uri.tryParse(path); + if (uri == null) return pipelines; + path = uri.path; + } + final hash = path.indexOf('#'); + if (hash != -1) path = path.substring(0, hash); + final query = path.indexOf('?'); + if (query != -1) path = path.substring(0, query); + + final segments = []; + for (final raw in path.split('/')) { + if (raw.isEmpty) continue; + try { + segments.add(Uri.decodeComponent(raw)); + } on ArgumentError { + return pipelines; + } + } + if (segments.isEmpty) return pipelines; + + return switch (segments.first) { + 'pipelines' when segments.length == 1 => pipelines, + 'runs' when segments.length == 1 => runs, + 'runs' when segments.length == 2 => _runRoute(segments[1]), + 'chat' when segments.length == 1 => chat, + 'settings' when segments.length == 1 => settings, + _ => pipelines, + }; + } + + static AppRoute _runRoute(String value) { + if (!RegExp(r'^[0-9]+$').hasMatch(value)) return pipelines; + final id = int.tryParse(value); + if (id == null || id <= 0) return pipelines; + return AppRoute(AppRouteKind.runs, runId: id); + } + + @override + bool operator ==(Object other) => + other is AppRoute && other.kind == kind && other.runId == runId; + + @override + int get hashCode => Object.hash(kind, runId); + + @override + String toString() => path; +} + +/// `AppRoute.run(3)` reads better than a constructor named after a field. +class _RunRouteFactory { + const _RunRouteFactory(); + + AppRoute call(int id) => AppRoute(AppRouteKind.runs, runId: id); +} diff --git a/app/lib/application/app_router.dart b/app/lib/application/app_router.dart new file mode 100644 index 00000000..44c87efb --- /dev/null +++ b/app/lib/application/app_router.dart @@ -0,0 +1,106 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import 'app_route.dart'; + +/// Parses the browser (or platform) location into the app's routes. +class AppRouteParser extends RouteInformationParser { + const AppRouteParser(); + + @override + Future parseRouteInformation( + RouteInformation routeInformation, + ) async => AppRoute.parse(routeInformation.uri.path); + + @override + RouteInformation restoreRouteInformation(AppRoute configuration) => + RouteInformation(uri: Uri(path: configuration.path)); +} + +/// Owns the app's current route and builds the shell for it. +/// +/// Route changes made by the operator go through [goTo]; the Router reports +/// them as browser history entries. Browser Back/Forward and deep links arrive +/// through [setNewRoutePath] and update the same route. +class AppRouterDelegate extends RouterDelegate with ChangeNotifier { + AppRouterDelegate({ + required this.builder, + required this.onPopToRuns, + required this.cupertino, + AppRoute initial = AppRoute.pipelines, + }) : _route = initial; + + final Widget Function(BuildContext context, AppRoute route) builder; + + /// Called when a system Back belongs to the Runs detail, not the app stack. + final VoidCallback onPopToRuns; + + final bool cupertino; + + final _navigatorKey = GlobalKey(); + static const _pageKey = ValueKey('pipelines-shell'); + + AppRoute _route; + + AppRoute get route => _route; + + @override + AppRoute get currentConfiguration => _route; + + /// A single-page Navigator supplies the Overlay, overlay portals and route + /// context that native controls (action sheets, tooltips) require. The page + /// key is stable, so changing the route updates the shell in place instead of + /// remounting it and losing the open run. + @override + Widget build(BuildContext context) { + final child = builder(context, _route); + return Navigator( + key: _navigatorKey, + pages: [ + if (cupertino) + CupertinoPage(key: _pageKey, child: child) + else + MaterialPage(key: _pageKey, child: child), + ], + onDidRemovePage: (_) {}, + ); + } + + @override + Future setInitialRoutePath(AppRoute configuration) async { + _route = configuration; + } + + @override + Future setNewRoutePath(AppRoute configuration) async { + if (configuration == _route) return; + _route = configuration; + notifyListeners(); + } + + @override + Future popRoute() async { + if (_route.runId == null) return false; + onPopToRuns(); + return true; + } + + /// Records a user move; the Router turns the new configuration into a + /// history entry (or a replacement when it already matches the location). + void goTo(AppRoute route) { + if (route == _route) return; + _route = route; + notifyListeners(); + } +} + +/// The location a web launch starts at, or the Pipelines list elsewhere. +/// +/// Only the path is meaningful to [AppRouteParser]; the origin stays out of +/// route configuration so a serialised route is always app-relative. +RouteInformation initialRouteInformation() { + if (!kIsWeb) return RouteInformation(uri: Uri(path: '/pipelines')); + final path = Uri.base.path; + return RouteInformation(uri: Uri(path: path.isEmpty ? '/' : path)); +} diff --git a/app/lib/application/app_session.dart b/app/lib/application/app_session.dart new file mode 100644 index 00000000..ef205653 --- /dev/null +++ b/app/lib/application/app_session.dart @@ -0,0 +1,168 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../core/api_gateway.dart'; +import '../core/transport/pipelines_client.dart'; + +/// Whether this connection's send-only `subscribe` was accepted. +/// +/// A server that never acks leaves this [pending]; only an explicit refusal +/// makes the session report that live updates are unavailable, so the UI never +/// guesses "not live" from silence. +enum RunSubscriptionState { pending, live, refused } + +/// Owns the one app-wide Pipelines socket and its run-event watch. +/// +/// The client reconnects on its own; this session re-sends the send-only +/// `subscribe` on every connected transition because a new socket has no +/// watch, and drops it deliberately with `unsubscribe` when the app stops. +class AppSession extends ChangeNotifier { + AppSession({required this.endpoint, PipelinesClient? client}) + : _client = client ?? PipelinesClient() { + _states = _client.states.listen(_onState); + _frames = _client.frames.listen(_onFrame); + } + + final Uri? endpoint; + final PipelinesClient _client; + late final StreamSubscription _states; + late final StreamSubscription _frames; + ConnectionState _connection = const ConnectionState(ConnectionKind.idle); + bool _subscribed = false, _disposed = false, _everConnected = false; + int _connectionEpoch = 0; + RunSubscriptionState _subscription = RunSubscriptionState.pending; + String _subscriptionError = ''; + String? _subscribeRequest; + + ApiGateway get gateway => _client; + ConnectionState get connection => _connection; + bool get connected => _connection.kind == ConnectionKind.connected; + + /// True once any connection has succeeded. The Runs destination shows the + /// full connection screen before this, then keeps the loaded screen mounted + /// through later drops instead of discarding the operator's place. + bool get everConnected => _everConnected; + + RunSubscriptionState get subscription => _subscription; + String get subscriptionError => _subscriptionError; + + /// Advances on every connected transition. The Runs destination keys the + /// screen's reload with this so a reconnect re-reads the list and the open + /// detail without remounting the screen or losing its selection. + int get connectionEpoch => _connectionEpoch; + + /// Connects the shared socket. A missing endpoint is a configuration state, + /// so this is a no-op rather than a guessed endpoint. + Future start() async { + if (_disposed || endpoint == null) return; + await _client.connect(endpoint!); + } + + /// Retries now: reopens a disconnected socket, or repeats a refused watch on + /// a healthy one. + Future retry() async { + if (connected) { + resubscribe(); + return; + } + await start(); + } + + /// Repeats the send-only watch on the current socket. Used when the server + /// explicitly refused the previous `subscribe`. + void resubscribe() { + if (_disposed) return; + _subscribed = false; + _subscribeRequest = null; + _subscription = RunSubscriptionState.pending; + _subscriptionError = ''; + _subscribe(); + notifyListeners(); + } + + /// Stops the watch and the socket without disposing the session, so a later + /// [start] can open a fresh connection. + Future stop() async { + if (_disposed) return; + _sendUnsubscribe(); + await _client.disconnect(); + } + + void _onState(ConnectionState state) { + if (_disposed) return; + final wasConnected = connected; + _connection = state; + if (state.kind == ConnectionKind.connected) { + _everConnected = true; + _connectionEpoch++; + _subscription = RunSubscriptionState.pending; + _subscriptionError = ''; + _subscribe(); + } else if (wasConnected) { + _subscribed = false; + _subscribeRequest = null; + _subscription = RunSubscriptionState.pending; + _subscriptionError = ''; + } + notifyListeners(); + } + + void _onFrame(JsonMap frame) { + if (_disposed) return; + final id = frame['id']; + if (id is! String || id != _subscribeRequest) return; + switch (frame['type']) { + case 'subscribe': + _subscription = RunSubscriptionState.live; + _subscriptionError = ''; + break; + case 'error': + _subscription = RunSubscriptionState.refused; + final reason = '${frame['error'] ?? ''}'.trim(); + _subscriptionError = reason.isEmpty + ? 'Live run updates are unavailable.' + : reason; + break; + default: + return; + } + notifyListeners(); + } + + void _subscribe() { + if (_subscribed || !connected) return; + try { + _subscribeRequest = _client.sendOnly('subscribe', const { + 'workspace': '', + }); + _subscribed = true; + } on NotConnectedError { + // A close raced the connected state; the next connected transition + // subscribes instead of leaving a half-registered watch. + } + } + + void _sendUnsubscribe() { + if (!_subscribed) return; + _subscribed = false; + _subscribeRequest = null; + if (!connected) return; + try { + _client.sendOnly('unsubscribe'); + } on NotConnectedError { + // The socket already closed, which drops the watch server-side. + } + } + + @override + void dispose() { + if (_disposed) return; + _disposed = true; + _sendUnsubscribe(); + unawaited(_states.cancel()); + unawaited(_frames.cancel()); + unawaited(_client.dispose()); + super.dispose(); + } +} diff --git a/app/lib/application/app_url_strategy.dart b/app/lib/application/app_url_strategy.dart new file mode 100644 index 00000000..db9fd768 --- /dev/null +++ b/app/lib/application/app_url_strategy.dart @@ -0,0 +1,10 @@ +import 'app_url_strategy_stub.dart' + if (dart.library.js_interop) 'app_url_strategy_web.dart' + as platform; + +/// Chooses the URL form the app's routes use. +/// +/// Web serves real paths (`/runs/1`) so a route can be bookmarked, opened +/// directly and handled by browser Back/Forward; other platforms keep their +/// in-memory route state. +void useAppUrlStrategy() => platform.useAppUrlStrategy(); diff --git a/app/lib/application/app_url_strategy_stub.dart b/app/lib/application/app_url_strategy_stub.dart new file mode 100644 index 00000000..04f5e160 --- /dev/null +++ b/app/lib/application/app_url_strategy_stub.dart @@ -0,0 +1 @@ +void useAppUrlStrategy() {} diff --git a/app/lib/application/app_url_strategy_web.dart b/app/lib/application/app_url_strategy_web.dart new file mode 100644 index 00000000..3d682e7a --- /dev/null +++ b/app/lib/application/app_url_strategy_web.dart @@ -0,0 +1,3 @@ +import 'package:flutter_web_plugins/url_strategy.dart'; + +void useAppUrlStrategy() => usePathUrlStrategy(); diff --git a/app/lib/application/bootstrap.dart b/app/lib/application/bootstrap.dart new file mode 100644 index 00000000..85accfc4 --- /dev/null +++ b/app/lib/application/bootstrap.dart @@ -0,0 +1,20 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +import 'app_url_strategy.dart'; +import 'pipelines_app.dart'; +import 'server_endpoint.dart'; + +/// Native builds must supply their server explicitly; there is no baked host. +const configuredServerUrl = String.fromEnvironment('PIPELINES_SERVER_URL'); + +/// Resolves the endpoint for this launch and starts the normal composition. +void runPipelinesApp({Uri? base, String configured = configuredServerUrl}) { + useAppUrlStrategy(); + final server = ServerEndpoint.resolve( + base: base ?? Uri.base, + web: kIsWeb, + configured: configured, + ); + runApp(PipelinesApp(server: server)); +} diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart new file mode 100644 index 00000000..99248589 --- /dev/null +++ b/app/lib/application/pipelines_app.dart @@ -0,0 +1,129 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +import '../core/transport/pipelines_client.dart'; +import '../shell/adaptive_shell.dart'; +import '../shell/destination.dart'; +import 'app.dart'; +import 'app_route.dart'; +import 'app_router.dart'; +import 'app_session.dart'; +import 'runs_destination.dart'; +import 'server_endpoint.dart'; + +/// Composes the live application around one [AppSession] and one [Router]. +/// +/// Tests may inject the client and route-information provider; the session +/// owns the socket either way, so there is never a second app-level connection. +class PipelinesApp extends StatefulWidget { + const PipelinesApp({ + super.key, + required this.server, + this.client, + this.cupertino, + this.routeInformationProvider, + }); + + final ServerEndpoint server; + final PipelinesClient? client; + final bool? cupertino; + + /// Test seam: the Router's initial and subsequent route information. + final RouteInformationProvider? routeInformationProvider; + + @override + State createState() => _PipelinesAppState(); +} + +class _PipelinesAppState extends State { + late final AppSession _session; + late final AppRouterDelegate _delegate; + late final RouteInformationProvider _provider; + late final bool _ownsProvider; + late final RouterConfig _config; + late final bool _cupertino; + + @override + void initState() { + super.initState(); + _session = AppSession(endpoint: widget.server.uri, client: widget.client); + _ownsProvider = widget.routeInformationProvider == null; + _provider = + widget.routeInformationProvider ?? + PlatformRouteInformationProvider( + initialRouteInformation: initialRouteInformation(), + ); + // A malformed or unknown boot path renders Pipelines, so make the address + // bar agree with the rendered destination instead of showing a dead link. + final initial = AppRoute.parse(_provider.value.uri.path); + if (_provider.value.uri.path != initial.path) { + _provider.routerReportsNewRouteInformation( + RouteInformation(uri: Uri(path: initial.path)), + type: RouteInformationReportingType.neglect, + ); + } + _cupertino = widget.cupertino ?? _platformIsCupertino; + _delegate = AppRouterDelegate( + initial: initial, + cupertino: _cupertino, + onPopToRuns: () => _delegate.goTo(AppRoute.runs), + builder: _buildShell, + ); + _config = RouterConfig( + routeInformationParser: const AppRouteParser(), + routerDelegate: _delegate, + routeInformationProvider: _provider, + ); + unawaited(_session.start()); + } + + @override + void dispose() { + _delegate.dispose(); + if (_ownsProvider) { + (_provider as PlatformRouteInformationProvider).dispose(); + } + _session.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => + MyApp.router(cupertino: _cupertino, routerConfig: _config); + + Widget _buildShell(BuildContext context, AppRoute route) => AdaptiveShell( + cupertino: _cupertino, + destination: _destinationOf(route.kind), + onDestinationSelected: (destination) => + _delegate.goTo(_routeOf(destination)), + destinationBodies: { + AppDestination.runs: (_) => RunsDestination( + session: _session, + server: widget.server, + initialRunId: route.runId, + onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)), + onBack: () => _delegate.goTo(AppRoute.runs), + ), + }, + ); + + AppDestination _destinationOf(AppRouteKind kind) => switch (kind) { + AppRouteKind.pipelines => AppDestination.pipelines, + AppRouteKind.runs => AppDestination.runs, + AppRouteKind.chat => AppDestination.chat, + AppRouteKind.settings => AppDestination.settings, + }; + + AppRoute _routeOf(AppDestination destination) => switch (destination) { + AppDestination.pipelines => AppRoute.pipelines, + AppDestination.runs => AppRoute.runs, + AppDestination.chat => AppRoute.chat, + AppDestination.settings => AppRoute.settings, + }; + + bool get _platformIsCupertino => + defaultTargetPlatform == TargetPlatform.iOS || + defaultTargetPlatform == TargetPlatform.macOS; +} diff --git a/app/lib/application/runs_destination.dart b/app/lib/application/runs_destination.dart new file mode 100644 index 00000000..760f439e --- /dev/null +++ b/app/lib/application/runs_destination.dart @@ -0,0 +1,249 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../core/transport/connection_state.dart'; +import '../features/runs/screen.dart'; +import '../ui/adaptive/host.dart'; +import 'app_session.dart'; +import 'server_endpoint.dart'; + +/// The Runs destination: the loaded screen plus an honest connection status. +/// +/// Before the first successful connection there is nothing to show, so the +/// destination is a full connection screen. After that the screen stays +/// mounted through drops and reconnects: a status banner reports reconnecting +/// or not live, and the screen reloads in place without losing the open run. +class RunsDestination extends StatelessWidget { + const RunsDestination({ + super.key, + required this.session, + required this.server, + this.initialRunId, + this.onRunSelected, + this.onBack, + }); + + final AppSession session; + final ServerEndpoint server; + final int? initialRunId; + final ValueChanged? onRunSelected; + final VoidCallback? onBack; + + @override + Widget build(BuildContext context) => AnimatedBuilder( + animation: session, + builder: (context, _) { + final cupertino = usesCupertinoHost(context); + if (server.requiresConfiguration || server.error != null) { + return _ConnectionScreen( + session: session, + server: server, + cupertino: cupertino, + ); + } + if (!session.everConnected) { + if (session.connected) return _runsScreen(); + return _ConnectionScreen( + session: session, + server: server, + cupertino: cupertino, + ); + } + return Column( + children: [ + if (!session.connected || + session.subscription == RunSubscriptionState.refused) + _ConnectionBanner(session: session, cupertino: cupertino), + Expanded(child: _runsScreen()), + ], + ); + }, + ); + + Widget _runsScreen() => RunsScreen( + gateway: session.gateway, + initialRunId: initialRunId, + syncToken: session.connectionEpoch, + onRunSelected: onRunSelected, + onBack: onBack, + ); +} + +class _ConnectionScreen extends StatelessWidget { + const _ConnectionScreen({ + required this.session, + required this.server, + required this.cupertino, + }); + + final AppSession session; + final ServerEndpoint server; + final bool cupertino; + + @override + Widget build(BuildContext context) { + final state = session.connection; + if (server.requiresConfiguration) { + return _status( + context, + title: 'Server endpoint not configured', + detail: + 'Build the native app with an explicit Pipelines endpoint, for ' + 'example --dart-define=PIPELINES_SERVER_URL=ws://host:port/connect.', + ); + } + if (server.error != null) { + return _status(context, title: server.error!, detail: ''); + } + // Only the very first attempt is "connecting". A failed attempt keeps the + // same honest unavailable state while the client retries behind it, so the + // screen no longer flickers between unavailable and connecting. + if (state.kind == ConnectionKind.connecting && state.attempt <= 1) { + return _status( + context, + title: 'Connecting to Pipelines…', + detail: '', + progress: true, + ); + } + return _status( + context, + title: 'Pipelines server unavailable', + detail: state.retrying + ? 'Retrying automatically. Check that the Pipelines server is running.' + : 'Check that the Pipelines server is running, then try again.', + onRetry: session.retry, + ); + } + + Widget _status( + BuildContext context, { + required String title, + required String detail, + bool progress = false, + VoidCallback? onRetry, + }) { + final theme = Theme.of(context); + return Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (progress) + Padding( + padding: const EdgeInsets.only(bottom: 12), + child: cupertino + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + ), + Semantics( + liveRegion: true, + child: Text( + title, + textAlign: TextAlign.center, + style: cupertino + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : theme.textTheme.titleMedium, + ), + ), + if (detail.isNotEmpty) ...[ + const SizedBox(height: 8), + Text( + detail, + textAlign: TextAlign.center, + style: cupertino ? null : theme.textTheme.bodyMedium, + ), + ], + if (onRetry != null) ...[ + const SizedBox(height: 16), + if (cupertino) + CupertinoButton(onPressed: onRetry, child: const Text('Retry')) + else + FilledButton(onPressed: onRetry, child: const Text('Retry')), + ], + ], + ), + ), + ); + } +} + +/// A compact status bar above the retained Runs screen. +class _ConnectionBanner extends StatelessWidget { + const _ConnectionBanner({required this.session, required this.cupertino}); + + final AppSession session; + final bool cupertino; + + @override + Widget build(BuildContext context) { + final state = session.connection; + final refused = session.subscription == RunSubscriptionState.refused; + final reconnecting = + !session.connected && + (state.kind == ConnectionKind.connecting || state.retrying); + final String title; + final String detail; + final VoidCallback onRetry; + if (session.connected && refused) { + title = 'Not live — run updates are unavailable.'; + detail = session.subscriptionError; + onRetry = session.resubscribe; + } else if (reconnecting) { + title = 'Reconnecting to Pipelines…'; + detail = ''; + onRetry = session.retry; + } else { + title = 'Not live — Pipelines server unavailable.'; + detail = 'Check that the Pipelines server is running.'; + onRetry = session.retry; + } + final textStyle = cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodyMedium; + return ColoredBox( + color: cupertino + ? CupertinoDynamicColor.resolve(CupertinoColors.systemGrey5, context) + : Theme.of(context).colorScheme.surfaceContainerHighest, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Row( + children: [ + if (reconnecting) ...[ + cupertino + ? const CupertinoActivityIndicator(radius: 7) + : const SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator(strokeWidth: 2), + ), + const SizedBox(width: 10), + ], + Expanded( + child: Semantics( + liveRegion: true, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: textStyle), + if (detail.isNotEmpty) Text(detail, style: textStyle), + ], + ), + ), + ), + const SizedBox(width: 8), + if (cupertino) + CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onRetry, + child: const Text('Retry'), + ) + else + TextButton(onPressed: onRetry, child: const Text('Retry')), + ], + ), + ), + ); + } +} diff --git a/app/lib/application/server_endpoint.dart b/app/lib/application/server_endpoint.dart new file mode 100644 index 00000000..84b1c3e8 --- /dev/null +++ b/app/lib/application/server_endpoint.dart @@ -0,0 +1,65 @@ +import '../core/transport/server_url.dart'; + +/// The single endpoints decision for an app launch. +/// +/// A web build is served by the Pipelines proxy itself, so its own page origin +/// is the only endpoint it may use: the browser reaches the same host over +/// ws(s) at `/connect`. A native build has no trustworthy origin and must be +/// given an explicit endpoint at build time; there is no default host. +class ServerEndpoint { + const ServerEndpoint._({ + this.uri, + this.error, + this.requiresConfiguration = false, + }); + + /// Validated websocket endpoint, or null when configuration is missing or + /// invalid. Never a guessed fallback. + final Uri? uri; + + /// Why no endpoint could be resolved, shown verbatim by the connection gate. + final String? error; + + /// Native builds without an explicit endpoint. This is a configuration + /// state, not a server error, so the gate can explain the required setting. + final bool requiresConfiguration; + + static ServerEndpoint resolve({ + required Uri base, + required bool web, + String configured = '', + }) { + if (web) { + if ((base.scheme != 'http' && base.scheme != 'https') || + base.host.isEmpty) { + return const ServerEndpoint._( + error: + 'The Pipelines endpoint is inferred from the page URL, ' + 'which is not HTTP(S).', + ); + } + final secure = base.scheme == 'https'; + final sameOrigin = Uri( + scheme: secure ? 'wss' : 'ws', + host: base.host, + port: base.hasPort ? base.port : null, + path: '/connect', + ); + return _validated(sameOrigin); + } + final value = configured.trim(); + if (value.isEmpty) { + return const ServerEndpoint._(requiresConfiguration: true); + } + return _validated(Uri.tryParse(value) ?? Uri()); + } + + static ServerEndpoint _validated(Uri value) { + try { + final endpoint = ServerUrl.validate(value.toString()); + return ServerEndpoint._(uri: Uri.parse(endpoint.wsUrl)); + } on FormatException catch (error) { + return ServerEndpoint._(error: error.message); + } + } +} diff --git a/app/lib/features/runs/domain/run_models.dart b/app/lib/features/runs/domain/run_models.dart index 0c2ff344..0f0d4941 100644 --- a/app/lib/features/runs/domain/run_models.dart +++ b/app/lib/features/runs/domain/run_models.dart @@ -10,6 +10,11 @@ const runStates = [ 'interrupted', ]; +/// The largest millisecond value [DateTime] supports, and also exactly +/// representable by the web's JavaScript numbers. The previous +/// `0x7fffffffffffffff` literals failed dart2js compilation. +const int _maxMillis = 8640000000000000; + ({String label, String? pipeline}) runIdentity(dynamic title, dynamic name) { final stored = '${title ?? ''}'.trim(); return ( @@ -116,25 +121,22 @@ List sortRuns(List runs, {String sort = 'newest_first'}) { int primary; switch (sort) { case 'oldest_first': - primary = cmp(at ?? 0x7fffffffffffffff, bt ?? 0x7fffffffffffffff); + primary = cmp(at ?? _maxMillis, bt ?? _maxMillis); break; case 'longest_duration': primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0); if (primary == 0) primary = cmp(duration(b) ?? -1, duration(a) ?? -1); if (primary == 0) { - primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff); + primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis); } break; case 'shortest_duration': primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0); if (primary == 0) { - primary = cmp( - duration(a) ?? 0x7fffffffffffffff, - duration(b) ?? 0x7fffffffffffffff, - ); + primary = cmp(duration(a) ?? _maxMillis, duration(b) ?? _maxMillis); } if (primary == 0) { - primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff); + primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis); } break; case 'pipeline_name': @@ -142,7 +144,7 @@ List sortRuns(List runs, {String sort = 'newest_first'}) { '${b['name'] ?? ''}'.toLowerCase(), ); if (primary == 0) { - primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff); + primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis); } break; case 'status': @@ -150,11 +152,11 @@ List sortRuns(List runs, {String sort = 'newest_first'}) { '${b['status'] ?? ''}'.toLowerCase(), ); if (primary == 0) { - primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff); + primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis); } break; default: - primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff); + primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis); } return primary == 0 ? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0) diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index 3e2630c8..607dde93 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -1,80 +1,113 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/cupertino.dart'; +import 'package:flutter/widgets.dart'; import '../../core/api_gateway.dart'; import 'data/runs_repository.dart'; +import 'ui/run_detail_view.dart'; import 'ui/runs_controller.dart'; import 'ui/runs_list.dart'; -import 'ui/run_detail_view.dart'; +/// The runs destination's list/detail switch. +/// +/// The controller's `selectedRunId` is the only selection source, so an +/// initial run, a pending detail, a failed detail, Back and a route change all +/// navigate the same way. The shell owns the app bar; this screen adds no +/// second one. class RunsScreen extends StatefulWidget { - const RunsScreen({super.key, required this.gateway, this.initialRunId}); + const RunsScreen({ + super.key, + required this.gateway, + this.initialRunId, + this.syncToken = 0, + this.onRunSelected, + this.onBack, + }); + final ApiGateway gateway; + + /// The run the current route names, or null for the list. final int? initialRunId; + /// Advances when the shared socket is replaced. The loaded screen refreshes + /// in place instead of being remounted, so its selection survives. + final int syncToken; + + final ValueChanged? onRunSelected; + final VoidCallback? onBack; + @override State createState() => _RunsScreenState(); } class _RunsScreenState extends State { - late RunsController controller; - num? _selectedRunId; + late final RunsController controller; + num? _shownRunId; + @override void initState() { super.initState(); controller = RunsController(RunsRepository(widget.gateway)); controller.listen(widget.gateway.frames); - controller.addListener(_changed); + controller.addListener(_selectionChanged); controller.load(widget.initialRunId); } - void _changed() { + @override + void didUpdateWidget(covariant RunsScreen oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.syncToken != oldWidget.syncToken) { + controller.resync(); + } + if (widget.initialRunId != oldWidget.initialRunId) { + final id = widget.initialRunId; + if (id == null) { + if (controller.selectedRunId != null) controller.back(); + } else if (controller.selectedRunId != id) { + controller.select(id); + } + } + } + + /// Rebuild the switch only when the selection changes. Detail progress and + /// live updates are already watched by [RunDetailView] and [RunsList], so + /// this avoids a second whole-detail rebuild per notification. + void _selectionChanged() { + final selected = controller.selectedRunId; + if (selected == _shownRunId) return; + _shownRunId = selected; if (mounted) setState(() {}); } + void _select(num id) { + controller.select(id); + widget.onRunSelected?.call(id.toInt()); + } + + void _back() { + controller.back(); + widget.onBack?.call(); + } + @override void dispose() { - controller.removeListener(_changed); + controller.removeListener(_selectionChanged); controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { - final isCupertino = Theme.of(context).platform == TargetPlatform.iOS; - final selected = _selectedRunId != null; - final content = Stack( + final selected = controller.selectedRunId != null; + return Stack( children: [ - Offstage( - offstage: selected, - child: RunsList(controller: controller, onSelected: (id) { - setState(() => _selectedRunId = id); - controller.select(id); - }), - ), - if (selected) - RunDetailView( - controller: controller, - onBack: () { - controller.back(); - setState(() => _selectedRunId = null); - }, + AnimatedBuilder( + animation: controller, + builder: (context, _) => Offstage( + offstage: selected, + child: RunsList(controller: controller, onSelected: _select), ), + ), + if (selected) RunDetailView(controller: controller, onBack: _back), ], ); - if (isCupertino) { - return CupertinoPageScaffold( - navigationBar: CupertinoNavigationBar( - middle: Text(selected ? 'Run ${controller.detail?['id'] ?? _selectedRunId}' : 'Runs'), - leading: selected ? CupertinoButton( - padding: EdgeInsets.zero, - onPressed: () { controller.back(); setState(() => _selectedRunId = null); }, - child: const Text('Runs'), - ) : null, - ), - child: SafeArea(child: content), - ); - } - return content; } } diff --git a/app/lib/features/runs/ui/run_detail_cupertino.dart b/app/lib/features/runs/ui/run_detail_cupertino.dart index 7c342a44..28fdddfe 100644 --- a/app/lib/features/runs/ui/run_detail_cupertino.dart +++ b/app/lib/features/runs/ui/run_detail_cupertino.dart @@ -36,7 +36,7 @@ Widget buildCupertinoRunDetail({ children: [ const Icon(CupertinoIcons.back), const SizedBox(width: 4), - const Text('Runs'), + const Text('Back'), ], ), ), diff --git a/app/lib/features/runs/ui/run_detail_material.dart b/app/lib/features/runs/ui/run_detail_material.dart index 84be2c77..27d98316 100644 --- a/app/lib/features/runs/ui/run_detail_material.dart +++ b/app/lib/features/runs/ui/run_detail_material.dart @@ -28,7 +28,7 @@ Widget buildMaterialRunDetail({ child: TextButton.icon( onPressed: onBack, icon: const Icon(Icons.arrow_back), - label: const Text('Runs'), + label: const Text('Back to list'), ), ), Text(detailTitle(run), style: theme.textTheme.headlineSmall), diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index b95962c3..0fda7ad7 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import '../../../ui/adaptive/host.dart'; import 'run_detail_content.dart'; import 'run_detail_cupertino.dart'; import 'run_detail_material.dart'; @@ -29,7 +30,7 @@ class _RunDetailViewState extends State { Widget build(BuildContext context) => AnimatedBuilder( animation: widget.controller, builder: (context, _) { - final cupertino = _usesCupertino(context); + final cupertino = usesCupertinoHost(context); final run = widget.controller.detail; if (run == null) return _placeholder(context, cupertino: cupertino); final prompt = detailPrompt(run); @@ -57,34 +58,24 @@ class _RunDetailViewState extends State { }, ); - /// CupertinoApp supplies CupertinoLocalizations only, while MaterialApp - /// supplies MaterialLocalizations. This distinguishes the two hosts without - /// assuming a desktop browser's target platform. - bool _usesCupertino(BuildContext context) => - Localizations.of(context, MaterialLocalizations) == - null; - Widget _placeholder(BuildContext context, {required bool cupertino}) { - if (widget.controller.detailLoading) { - return Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ + final loading = widget.controller.detailLoading; + final message = loading + ? 'Loading run details…' + : widget.controller.error ?? 'Run details unavailable.'; + // Back stays available while the detail is pending as well as after a + // failure, so a slow or refused request can never trap the destination. + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (loading) ...[ if (cupertino) const CupertinoActivityIndicator() else const CircularProgressIndicator(), const SizedBox(height: 12), - const Text('Loading run details…'), ], - ), - ); - } - final message = widget.controller.error ?? 'Run details unavailable.'; - return Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 24), child: Text(message, textAlign: TextAlign.center), @@ -93,12 +84,12 @@ class _RunDetailViewState extends State { if (cupertino) CupertinoButton( onPressed: widget.onBack, - child: const Text('Back to runs'), + child: const Text('Back to list'), ) else FilledButton( onPressed: widget.onBack, - child: const Text('Back to runs'), + child: const Text('Back to list'), ), ], ), diff --git a/app/lib/features/runs/ui/runs_controller.dart b/app/lib/features/runs/ui/runs_controller.dart index 977d8223..0dbd12f7 100644 --- a/app/lib/features/runs/ui/runs_controller.dart +++ b/app/lib/features/runs/ui/runs_controller.dart @@ -61,6 +61,16 @@ class RunsController extends ChangeNotifier { if (initialId != null) await select(initialId); } + /// Re-reads the list and the open detail after the socket was replaced. + /// + /// The selection is kept, so a reconnect refreshes in place instead of + /// discarding the detail the operator had open. + Future resync() async { + final selected = _selectedId; + await load(); + if (selected != null && _selectedId == selected) await select(selected); + } + Future select(num id) async { final token = ++_detailGeneration; _cancelDetailRefresh(); diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index 714d2d54..0f974eac 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -1,8 +1,8 @@ import 'package:flutter/cupertino.dart'; -import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; import '../domain/run_models.dart'; import 'runs_controller.dart'; @@ -16,15 +16,11 @@ class RunsList extends StatelessWidget { final RunsController controller; final ValueChanged onSelected; - bool get _isCupertino => - defaultTargetPlatform == TargetPlatform.iOS || - defaultTargetPlatform == TargetPlatform.macOS; - @override Widget build(BuildContext context) { if (controller.loading && controller.runs.isEmpty) { return Center( - child: _isCupertino + child: usesCupertinoHost(context) ? const CupertinoActivityIndicator() : const CircularProgressIndicator(), ); @@ -43,7 +39,7 @@ class RunsList extends StatelessWidget { if (controller.error != null) _inlineError(context), Padding( padding: const EdgeInsets.all(16), - child: _isCupertino + child: usesCupertinoHost(context) ? CupertinoSearchTextField( placeholder: 'Filter runs', onChanged: controller.setQuery, @@ -76,7 +72,7 @@ class RunsList extends StatelessWidget { children: [ Text(controller.error!), const SizedBox(height: 8), - _isCupertino + usesCupertinoHost(context) ? CupertinoButton( onPressed: controller.load, child: const Text('Retry'), @@ -94,7 +90,7 @@ class RunsList extends StatelessWidget { child: Row( children: [ Expanded(child: Text(controller.error!)), - if (_isCupertino) + if (usesCupertinoHost(context)) CupertinoButton( onPressed: controller.load, child: const Text('Retry'), @@ -106,7 +102,7 @@ class RunsList extends StatelessWidget { ); Widget _selectors(BuildContext context) { - if (_isCupertino) { + if (usesCupertinoHost(context)) { return Wrap( spacing: 8, children: [ @@ -206,7 +202,7 @@ class RunsList extends StatelessWidget { final title = identity.label.isEmpty ? 'Run $id' : identity.label; final subtitle = '${run['name'] ?? 'Pipeline unavailable'} · ${run['created_at'] ?? 'Time unavailable'}${run['scheduled'] == true ? ' · Scheduled' : ''}'; - if (_isCupertino) { + if (usesCupertinoHost(context)) { return CupertinoListTile( title: Text(title), subtitle: Text(subtitle), diff --git a/app/lib/main.dart b/app/lib/main.dart index 53ef59d8..ef65859c 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -1,40 +1,7 @@ -import 'package:flutter/cupertino.dart'; -import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; - -import 'shell/adaptive_shell.dart'; -import 'shell/destination.dart'; +import 'application/bootstrap.dart'; +export 'application/app.dart' show MyApp; export 'shell/adaptive_shell.dart'; export 'shell/destination.dart'; -void main() => runApp(const MyApp()); - -class MyApp extends StatelessWidget { - const MyApp({super.key, this.destinationBodies = const {}, this.cupertino}); - - final Map destinationBodies; - final bool? cupertino; - - @override - Widget build(BuildContext context) { - final platform = defaultTargetPlatform; - if (cupertino ?? - (platform == TargetPlatform.iOS || platform == TargetPlatform.macOS)) { - return CupertinoApp( - title: 'Pipelines', - home: AdaptiveShell( - destinationBodies: destinationBodies, - cupertino: true, - ), - ); - } - return MaterialApp( - title: 'Pipelines', - theme: ThemeData(), - darkTheme: ThemeData(brightness: Brightness.dark), - themeMode: ThemeMode.system, - home: AdaptiveShell(destinationBodies: destinationBodies), - ); - } -} +void main() => runPipelinesApp(); diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index 0def351a..85a5d3e0 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -8,20 +8,46 @@ class AdaptiveShell extends StatefulWidget { super.key, this.destinationBodies = const {}, this.cupertino = false, + this.destination, + this.onDestinationSelected, }); final Map destinationBodies; final bool cupertino; + /// The destination a route owner selected. When null the shell keeps its own + /// selection, which preserves the plain-shell tests and native composition. + final AppDestination? destination; + final ValueChanged? onDestinationSelected; + @override State createState() => _AdaptiveShellState(); } class _AdaptiveShellState extends State { - AppDestination _selected = AppDestination.pipelines; + late AppDestination _selected; - void _select(AppDestination destination) => - setState(() => _selected = destination); + @override + void initState() { + super.initState(); + _selected = widget.destination ?? AppDestination.pipelines; + } + + @override + void didUpdateWidget(covariant AdaptiveShell oldWidget) { + super.didUpdateWidget(oldWidget); + final destination = widget.destination; + if (destination != null) _selected = destination; + } + + void _select(AppDestination destination) { + final callback = widget.onDestinationSelected; + if (callback != null) { + callback(destination); + return; + } + setState(() => _selected = destination); + } List _items(T Function(AppDestination) build) => AppDestination.values.map(build).toList(); diff --git a/app/lib/ui/adaptive/host.dart b/app/lib/ui/adaptive/host.dart new file mode 100644 index 00000000..80f68825 --- /dev/null +++ b/app/lib/ui/adaptive/host.dart @@ -0,0 +1,10 @@ +import 'package:flutter/material.dart'; + +/// Whether the nearest app host is a Cupertino one. +/// +/// A `CupertinoApp` supplies Cupertino localizations only, while `MaterialApp` +/// supplies [MaterialLocalizations]. Checking the host avoids guessing from a +/// desktop browser's target platform and keeps one answer for every control. +bool usesCupertinoHost(BuildContext context) => + Localizations.of(context, MaterialLocalizations) == + null; diff --git a/app/notes/I1.md b/app/notes/I1.md new file mode 100644 index 00000000..7b59bbb8 --- /dev/null +++ b/app/notes/I1.md @@ -0,0 +1,119 @@ +# I1 — live Runs destination, routes and resilient connection + +## Change + +- `lib/application/` composes the real app separately from `main.dart`: + `bootstrap.dart` resolves the endpoint and starts the composition, + `pipelines_app.dart` owns one `AppSession` and one `Router`, + `runs_destination.dart` frames the Runs destination, and `app.dart` keeps the + injectable `MyApp` shell for existing widget tests. `main.dart` exports `MyApp` + and calls `runPipelinesApp()`. +- Web endpoint: the page origin from `Uri.base` over `ws(s)` at `/connect`, so + the same server that served the bundle is the live server. Native builds use + only the explicit `--dart-define=PIPELINES_SERVER_URL=ws://host:port/connect` + value; there is no baked host or fallback endpoint. +- **Routes/deep links (I1's second half):** the app now uses Flutter's `Router` + with a total `AppRoute` parser (`/pipelines`, `/runs`, `/runs/:id`, `/chat`, + `/settings`) and the path URL strategy (`flutter_web_plugins` declared as a + direct dependency). `/runs/1` opens that run directly, tab and run selection + push browser history, Back/Forward move between them, and a malformed or + unknown path renders Pipelines and is corrected to `/pipelines`. Non-web + platforms keep the same routes through the Router without an address bar. + A single-page `Navigator` inside the Router delegate supplies the Overlay + native controls need while keeping the shell state across route changes. +- **Reconnects keep the destination:** before the first successful connection + the destination is a full connection screen. After that the loaded Runs screen + stays mounted through drops: a compact status banner reports `Reconnecting to + Pipelines…` or `Not live — Pipelines server unavailable.` with a Retry action, + and `connectionEpoch` triggers an in-place list/detail refresh. The open run, + its scroll position and Back all survive the reconnect; the screen is not + remounted and the selection is not reset. +- **Honest connection copy:** the full gate no longer prints a raw transport + exception. A failed first attempt stays `Pipelines server unavailable` with + `Retrying automatically…` while the client retries instead of flickering to + `Connecting…` on every attempt. Only the first attempt shows `Connecting to + Pipelines…`. +- **Live-watch status:** `AppSession` now observes the send-only `subscribe` + ack/error. A server refusal is reported as `Not live — run updates are + unavailable.` with the server's own refusal reason and a Retry that repeats the + watch; silence (servers that never ack, like the fixture) is left pending + rather than guessed as "not live". +- `AppSession` owns the single shared `PipelinesClient` and its state stream. It + sends `subscribe` with `{workspace: ''}` on every connected transition and + `unsubscribe` on stop/dispose. +- `RunsScreen` consumes `controller.selectedRunId` as the only selection source; + a route change, an initial run, a pending/failed detail and Back all navigate + the same path. Removed the nested `CupertinoPageScaffold`/`CupertinoNavigationBar`; + the shell owns the single native bar. +- `RunDetailView` keeps Back available while the detail is pending as well as on + failure. The detail's back row and the pending/error action now read + `Back to list` (Cupertino's compact row reads `Back`), matching web's + accessible name instead of the ambiguous `Runs`. +- Cupertino-host detection is centralized in `lib/ui/adaptive/host.dart` and used + by the destination, detail and runs list instead of three different checks. +- Inherited web build defect: `run_models.dart` used `0x7fffffffffffffff` + sentinels, which dart2js cannot represent. Replaced them with the `DateTime` + maximum millisecond value (`8640000000000000`), also an exact JavaScript + number; sort behavior is unchanged. + +## Checks + +- `flutter test`: **86 passed** (12 new since the previous visit; the prior suite + plus route, reconnect-retention, subscribe-status and composition coverage). +- `flutter analyze`: **no issues**. +- `flutter build web` (normal `lib/main.dart`): **succeeded**. +- `dart format --output=none --set-exit-if-changed lib test tool`: clean. +- `git diff --check`: clean. + +## Browser acceptance + +`tool/runs_probe.mjs` ran real headless Chrome against the isolated loopback +fixture (`tool/runs_probe_server.mjs`) with a same-origin `/connect` WebSocket. +HTML MIME is checked before launch; body assertions use Flutter semantics and +Tesseract OCR of canvas-rendered text. The probe now also drives: + +- `Runs` tab → URL `/runs`; run row → `/runs/1`; browser Back → list at + `/runs`; browser Forward → detail at `/runs/1`. +- a direct `/runs/1` load opens the detail and leaves the address bar there. +- `/fixture/refuse` drops the socket and rejects upgrades: the open detail stays + visible, the banner reads `Reconnecting to Pipelines…`, no raw + `WebSocketException`/`Failed to connect` text is rendered, and the URL stays + `/runs/1`. +- accepting again plus Retry restores the same detail without a remount + (`subscribed`, `listRuns` and `getRun` all increase on the fixture). +- a fresh load while upgrades are refused shows the friendly + `Pipelines server unavailable` gate with no raw exception and does not flicker + back to `Connecting…`; Retry recovers the list. + +Probe result: `ok: true`, `subscribed: 4`, `listRuns: 5`, `getRun: 7`, +`dropped: 2`, `live: true`. Captures are in +`/Users/alan/.local/share/pipelines/data/artifacts/50/public/i1-fixes/` +(18 PNGs), including: + +- `i1-runs-phone-browser-back-list.png` +- `i1-runs-phone-browser-forward-detail.png` +- `i1-deeplink-run-1-phone.png` +- `i1-reconnect-detail-retained-phone.png` +- `i1-reconnect-detail-restored-phone.png` +- `i1-gate-unavailable-friendly-phone.png` +- `i1-gate-recovered-list-phone.png` +- `i1-material-deeplink-run-1-phone.png` — a Linux user-agent override selects + the Material host; the same deep link renders Material controls with the + `Back to list` action. + +The existing list/detail/pending/error/input/output/metrics captures were also +regenerated. No page exceptions were logged in the final probe run. + +## Limits + +- Read-only live authenticated smoke through the manager preview was not + performed: `http://127.0.0.1:8096/` requires auth. No credentials were + available without reading secrets. The preview was not restarted or replaced. +- Mobile builds/devices were not run; mobile is unverified. The shared Router + and single-page Navigator are used on all targets but only web was exercised. +- The fixture does not ack `subscribe` (by design), so the "live" ack path is + covered by widget tests; the refusal banner is covered by tests and the gate + by browser evidence. +- No real run was modified. No commit, push or deployment was made. +- Adding `flutter_web_plugins` to `pubspec.yaml` is the one dependency change; + it is required for path-style routes on web. diff --git a/app/pubspec.lock b/app/pubspec.lock index 8cdb6395..b36726e5 100644 --- a/app/pubspec.lock +++ b/app/pubspec.lock @@ -108,7 +108,7 @@ packages: source: sdk version: "0.0.0" flutter_web_plugins: - dependency: transitive + dependency: "direct main" description: flutter source: sdk version: "0.0.0" diff --git a/app/pubspec.yaml b/app/pubspec.yaml index b29fa9d1..fa4a079a 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -36,6 +36,8 @@ dependencies: cupertino_icons: ^1.0.8 web_socket_channel: ^3.0.3 shared_preferences: ^2.5.6 + flutter_web_plugins: + sdk: flutter dev_dependencies: flutter_test: diff --git a/app/test/application/app_route_test.dart b/app/test/application/app_route_test.dart new file mode 100644 index 00000000..598dce52 --- /dev/null +++ b/app/test/application/app_route_test.dart @@ -0,0 +1,52 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/app_route.dart'; + +void main() { + test('parses each destination and a run detail', () { + expect(AppRoute.parse('/pipelines'), AppRoute.pipelines); + expect(AppRoute.parse('/runs'), AppRoute.runs); + expect(AppRoute.parse('/runs/12'), AppRoute.run(12)); + expect(AppRoute.parse('/chat'), AppRoute.chat); + expect(AppRoute.parse('/settings'), AppRoute.settings); + }); + + 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('http://127.0.0.1:8096/runs/7?action=decide#top'), + AppRoute.run(7), + ); + expect(AppRoute.parse('/runs/7/'), AppRoute.run(7)); + }); + + test('a malformed or unknown location is the default Pipelines route', () { + for (final path in [ + '', + '/', + '/runs/abc', + '/runs/0', + '/runs/-1', + '/runs/1/extra', + '/pipelines/2', + '/chat/session', + '/unknown', + '/runs/%E0%A4%A', + ]) { + expect(AppRoute.parse(path), AppRoute.pipelines, reason: path); + } + }); + + test('serialises every route back to a parsable path', () { + for (final route in [ + AppRoute.pipelines, + AppRoute.runs, + AppRoute.run(3), + AppRoute.chat, + AppRoute.settings, + ]) { + expect(AppRoute.parse(route.path), route); + } + expect(AppRoute.run(3).path, '/runs/3'); + }); +} diff --git a/app/test/application/app_session_test.dart b/app/test/application/app_session_test.dart new file mode 100644 index 00000000..709db1b2 --- /dev/null +++ b/app/test/application/app_session_test.dart @@ -0,0 +1,148 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/app_session.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +Future flush() => Future.delayed(Duration.zero); + +Future waitFor(bool Function() condition, String reason) async { + for (var attempt = 0; attempt < 200; attempt++) { + if (condition()) return; + await Future.delayed(const Duration(milliseconds: 5)); + } + fail('Timed out: $reason'); +} + +List types(FakeChannel channel) => [ + for (final frame in channel.outgoing) + (jsonDecode(frame as String) as Map)['type'] as String, +]; + +void main() { + test( + 'start subscribes once, stop unsubscribes, and the app owns the socket', + () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final session = AppSession( + endpoint: Uri.parse('ws://example.test/connect'), + client: client, + ); + + await session.start(); + await flush(); + expect(session.connected, isTrue); + expect(types(channel), ['subscribe']); + final frame = jsonDecode(channel.outgoing.single as String) as Map; + expect(frame['workspace'], ''); + + await session.stop(); + await flush(); + expect(types(channel), ['subscribe', 'unsubscribe']); + expect(session.connected, isFalse); + session.dispose(); + }, + ); + + test('reconnect subscribes the new socket again', () async { + final first = FakeChannel()..readyCompleter.complete(); + final second = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) => sockets++ == 0 ? first : second, + backoffBase: const Duration(milliseconds: 5), + ); + final session = AppSession( + endpoint: Uri.parse('ws://example.test/connect'), + client: client, + ); + addTearDown(session.dispose); + + await session.start(); + await flush(); + expect(types(first), ['subscribe']); + expect(session.connectionEpoch, 1); + + first.incoming.addError(StateError('network drop')); + await waitFor( + () => sockets == 2 && session.connected && second.outgoing.isNotEmpty, + 'reconnected socket did not subscribe', + ); + expect(types(second), ['subscribe']); + expect(session.connectionEpoch, 2); + }); + + test('a subscribe ack marks the watch live, a refusal reports it', () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final session = AppSession( + endpoint: Uri.parse('ws://example.test/connect'), + client: client, + ); + addTearDown(session.dispose); + + await session.start(); + await flush(); + final subscribe = + jsonDecode(channel.outgoing.single as String) as Map; + expect(session.subscription, RunSubscriptionState.pending); + + channel.incoming.add( + jsonEncode({'id': subscribe['id'], 'type': 'subscribe'}), + ); + await flush(); + expect(session.subscription, RunSubscriptionState.live); + expect(session.subscriptionError, isEmpty); + + session.resubscribe(); + await flush(); + final repeated = + jsonDecode(channel.outgoing.last as String) as Map; + expect(repeated['type'], 'subscribe'); + channel.incoming.add( + jsonEncode({ + 'id': repeated['id'], + 'type': 'error', + 'error': 'too many run subscriptions on this connection', + }), + ); + await flush(); + expect(session.subscription, RunSubscriptionState.refused); + expect(session.subscriptionError, contains('too many run subscriptions')); + }); + + test('dispose drops the watch and releases the client', () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final session = AppSession( + endpoint: Uri.parse('ws://example.test/connect'), + client: client, + ); + + await session.start(); + await flush(); + session.dispose(); + await flush(); + + expect(types(channel), ['subscribe', 'unsubscribe']); + await expectLater( + client.connect(Uri.parse('ws://example.test/connect')), + throwsStateError, + ); + }); + + test('a missing endpoint is not replaced by a guessed connection', () async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final session = AppSession(endpoint: null, client: client); + addTearDown(session.dispose); + + await session.start(); + await flush(); + expect(channel.outgoing, isEmpty); + expect(session.connected, isFalse); + }); +} diff --git a/app/test/application/pipelines_app_test.dart b/app/test/application/pipelines_app_test.dart new file mode 100644 index 00000000..b92c3b41 --- /dev/null +++ b/app/test/application/pipelines_app_test.dart @@ -0,0 +1,177 @@ +import 'dart:convert'; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +ServerEndpoint webServer() => ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: true, +); + +Map? requestOf(FakeChannel channel, String type) => channel + .outgoing + .map((frame) => jsonDecode(frame as String) as Map) + .where((frame) => frame['type'] == type) + .firstOrNull; + +Future pumpApp( + WidgetTester tester, { + required FakeChannel channel, + required PipelinesClient client, + required PlatformRouteInformationProvider provider, +}) async { + await tester.pumpWidget( + PipelinesApp( + server: webServer(), + client: client, + cupertino: false, + routeInformationProvider: provider, + ), + ); + await tester.pump(); +} + +Future replyList( + WidgetTester tester, + FakeChannel channel, { + required List> runs, +}) async { + for ( + var attempt = 0; + attempt < 40 && requestOf(channel, 'list_runs') == null; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 5)); + } + final request = requestOf(channel, 'list_runs')!; + channel.incoming.add( + jsonEncode({'id': request['id'], 'type': 'runs', 'runs': runs}), + ); + await tester.pump(); + await tester.pump(); +} + +Future replyDetail( + WidgetTester tester, + FakeChannel channel, + num id, +) async { + for ( + var attempt = 0; + attempt < 40 && requestOf(channel, 'get_run') == null; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 5)); + } + final request = requestOf(channel, 'get_run')!; + expect(request['run_id'], id); + channel.incoming.add( + jsonEncode({ + 'id': request['id'], + 'type': 'run', + 'run_detail': {'id': id, 'title': 'Run $id', 'status': 'running'}, + }), + ); + await tester.pump(); + await tester.pump(); +} + +void main() { + testWidgets('a /runs/1 boot link opens that run and Back returns to /runs', ( + tester, + ) async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/runs/1')), + ); + addTearDown(provider.dispose); + + await pumpApp(tester, channel: channel, client: client, provider: provider); + await replyList( + tester, + channel, + runs: [ + {'id': 1, 'name': 'Deep-linked run', 'status': 'running'}, + ], + ); + await replyDetail(tester, channel, 1); + + expect(find.text('Run 1'), findsWidgets); + expect(find.text('Back to list'), findsOneWidget); + expect(provider.value.uri.path, '/runs/1'); + expect(find.text('Pipelines — Not implemented'), findsNothing); + + await tester.tap(find.text('Back to list')); + await tester.pump(); + expect(provider.value.uri.path, '/runs'); + expect(find.text('Deep-linked run'), findsWidgets); + }); + + testWidgets('tabs and run selection update the route; browser Back pops it', ( + tester, + ) async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')), + ); + addTearDown(provider.dispose); + + await pumpApp(tester, channel: channel, client: client, provider: provider); + expect(provider.value.uri.path, '/pipelines'); + + await tester.tap(find.text('Runs').last); + await tester.pump(); + expect(provider.value.uri.path, '/runs'); + + await replyList( + tester, + channel, + runs: [ + {'id': 2, 'name': 'Beta run', 'status': 'failed'}, + ], + ); + await tester.tap(find.text('Beta run')); + await tester.pump(); + expect(provider.value.uri.path, '/runs/2'); + await replyDetail(tester, channel, 2); + expect(find.text('Back to list'), findsOneWidget); + + // The engine's browser Back arrives as new route information. + await provider.didPushRouteInformation( + RouteInformation(uri: Uri.parse('/runs')), + ); + await tester.pump(); + expect(find.text('Beta run'), findsWidgets); + expect(find.text('Back to list'), findsNothing); + + // Forward re-opens the same run. + await provider.didPushRouteInformation( + RouteInformation(uri: Uri.parse('/runs/2')), + ); + await tester.pump(); + await replyDetail(tester, channel, 2); + expect(find.text('Back to list'), findsOneWidget); + }); + + testWidgets('a malformed boot path is corrected to /pipelines', ( + tester, + ) async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/runs/abc')), + ); + addTearDown(provider.dispose); + + await pumpApp(tester, channel: channel, client: client, provider: provider); + expect(provider.value.uri.path, '/pipelines'); + expect(find.text('Pipelines — Not implemented'), findsOneWidget); + }); +} diff --git a/app/test/application/runs_destination_test.dart b/app/test/application/runs_destination_test.dart new file mode 100644 index 00000000..abdd07fd --- /dev/null +++ b/app/test/application/runs_destination_test.dart @@ -0,0 +1,302 @@ +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/app_session.dart'; +import 'package:pipelines_app/application/runs_destination.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +ServerEndpoint webServer() => ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: true, +); + +Widget materialApp( + AppSession session, + ServerEndpoint server, { + int? initialRunId, + ValueChanged? onRunSelected, + VoidCallback? onBack, +}) => MaterialApp( + home: Scaffold( + body: RunsDestination( + session: session, + server: server, + initialRunId: initialRunId, + onRunSelected: onRunSelected, + onBack: onBack, + ), + ), +); + +Map? listRequest(FakeChannel channel) => channel.outgoing + .map((frame) => jsonDecode(frame as String) as Map) + .where((frame) => frame['type'] == 'list_runs') + .firstOrNull; + +Iterable> detailRequests(FakeChannel channel, int id) => + channel.outgoing + .map((frame) => jsonDecode(frame as String) as Map) + .where((frame) => frame['type'] == 'get_run' && frame['run_id'] == id); + +void main() { + testWidgets('gate explains missing native configuration without connecting', ( + tester, + ) async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final server = ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: false, + ); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + await tester.pumpWidget(materialApp(session, server)); + expect(find.text('Server endpoint not configured'), findsOneWidget); + expect(find.textContaining('PIPELINES_SERVER_URL'), findsOneWidget); + expect(find.byType(RunsScreen), findsNothing); + expect(channel.outgoing, isEmpty); + }); + + testWidgets('gate shows connecting, then mounts the normal runs screen', ( + tester, + ) async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + final starting = session.start(); + await tester.pumpWidget(materialApp(session, server)); + await tester.pump(); + expect(find.text('Connecting to Pipelines…'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + expect(find.byType(RunsScreen), findsNothing); + + channel.readyCompleter.complete(); + await starting; + await tester.pump(); + await tester.pump(); + expect(find.byType(RunsScreen), findsOneWidget); + + final list = listRequest(channel)!; + channel.incoming.add( + jsonEncode({ + 'id': list['id'], + 'type': 'runs', + 'runs': [ + {'id': 5, 'name': 'Live fixture run', 'status': 'succeeded'}, + ], + }), + ); + await tester.pump(); + expect(find.text('Live fixture run'), findsOneWidget); + }); + + testWidgets('a refused socket shows a friendly reason, never the exception', ( + tester, + ) async { + final channel = FakeChannel(); + final client = PipelinesClient( + channelFactory: (_) => channel, + backoffBase: const Duration(hours: 1), + backoffMax: const Duration(hours: 1), + ); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + final starting = session.start(); + channel.readyCompleter.completeError( + StateError('WebSocketChannelException: Failed to connect'), + ); + await starting; + await tester.pumpWidget(materialApp(session, server)); + await tester.pump(); + expect(find.text('Pipelines server unavailable'), findsOneWidget); + expect(find.textContaining('Retrying automatically'), findsOneWidget); + expect(find.textContaining('WebSocketChannelException'), findsNothing); + expect(find.widgetWithText(FilledButton, 'Retry'), findsOneWidget); + expect(find.byType(RunsScreen), findsNothing); + // The client keeps retrying by design; end the retry loop explicitly so + // the test does not leave a wall-clock timer behind. + session.dispose(); + }); + + testWidgets( + 'a drop keeps the list and reports reconnecting, not unavailable', + (tester) async { + final first = FakeChannel()..readyCompleter.complete(); + final second = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) => sockets++ == 0 ? first : second, + backoffBase: const Duration(milliseconds: 200), + ); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + await session.start(); + await tester.pumpWidget(materialApp(session, server)); + await tester.pump(); + await tester.pump(); + first.incoming.add( + jsonEncode({ + 'id': listRequest(first)!['id'], + 'type': 'runs', + 'runs': [ + {'id': 1, 'name': 'Before reconnect', 'status': 'running'}, + ], + }), + ); + await tester.pump(); + expect(find.text('Before reconnect'), findsOneWidget); + + first.incoming.addError(StateError('network drop')); + await tester.pump(); + expect(find.byType(RunsScreen), findsOneWidget); + expect(find.text('Reconnecting to Pipelines…'), findsOneWidget); + expect(find.text('Pipelines server unavailable'), findsNothing); + expect(find.text('Before reconnect'), findsOneWidget); + + for ( + var attempt = 0; + attempt < 40 && listRequest(second) == null; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 50)); + } + expect(listRequest(second), isNotNull); + expect(find.text('Reconnecting to Pipelines…'), findsNothing); + second.incoming.add( + jsonEncode({ + 'id': listRequest(second)!['id'], + 'type': 'runs', + 'runs': [ + {'id': 2, 'name': 'After reconnect', 'status': 'succeeded'}, + ], + }), + ); + await tester.pump(); + expect(find.text('After reconnect'), findsOneWidget); + expect(find.text('Before reconnect'), findsNothing); + }, + ); + + testWidgets( + 'reconnect keeps the open detail instead of resetting to the list', + (tester) async { + final first = FakeChannel()..readyCompleter.complete(); + final second = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) => sockets++ == 0 ? first : second, + backoffBase: const Duration(milliseconds: 10), + ); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + await session.start(); + await tester.pumpWidget(materialApp(session, server, initialRunId: 1)); + await tester.pump(); + await tester.pump(); + first.incoming.add( + jsonEncode({ + 'id': listRequest(first)!['id'], + 'type': 'runs', + 'runs': [ + {'id': 1, 'name': 'Open run', 'status': 'running'}, + ], + }), + ); + await tester.pump(); + final firstDetail = detailRequests(first, 1).single; + first.incoming.add( + jsonEncode({ + 'id': firstDetail['id'], + 'type': 'run', + 'run_detail': {'id': 1, 'title': 'Open run', 'status': 'running'}, + }), + ); + await tester.pump(); + expect(find.text('Open run'), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + + first.incoming.addError(StateError('network drop')); + await tester.pump(); + expect(find.byType(RunsScreen), findsOneWidget); + expect(find.text('Open run'), findsOneWidget); + expect(find.text('Reconnecting to Pipelines…'), findsOneWidget); + + for ( + var attempt = 0; + attempt < 60 && listRequest(second) == null; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 10)); + } + expect(listRequest(second), isNotNull); + second.incoming.add( + jsonEncode({ + 'id': listRequest(second)!['id'], + 'type': 'runs', + 'runs': [ + {'id': 1, 'name': 'Open run', 'status': 'running'}, + ], + }), + ); + for ( + var attempt = 0; + attempt < 20 && detailRequests(second, 1).isEmpty; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 10)); + } + final refreshed = detailRequests(second, 1).single; + expect(find.text('Open run'), findsOneWidget); + second.incoming.add( + jsonEncode({ + 'id': refreshed['id'], + 'type': 'run', + 'run_detail': {'id': 1, 'title': 'Open run', 'status': 'succeeded'}, + }), + ); + await tester.pump(); + expect(find.text('Open run'), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + }, + ); + + testWidgets('gate uses Cupertino progress without a Material ancestor', ( + tester, + ) async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + session.start(); + await tester.pumpWidget( + CupertinoApp( + home: CupertinoPageScaffold( + child: RunsDestination(session: session, server: server), + ), + ), + ); + await tester.pump(); + expect(find.text('Connecting to Pipelines…'), findsOneWidget); + expect(find.byType(CupertinoActivityIndicator), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(find.byType(Material), findsNothing); + }); +} diff --git a/app/test/application/server_endpoint_test.dart b/app/test/application/server_endpoint_test.dart new file mode 100644 index 00000000..d5d398d3 --- /dev/null +++ b/app/test/application/server_endpoint_test.dart @@ -0,0 +1,61 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; + +void main() { + test('web infers its own origin over ws at /connect', () { + final server = ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/runs?filter=active'), + web: true, + ); + expect(server.uri, Uri.parse('ws://127.0.0.1:8096/connect')); + expect(server.error, isNull); + expect(server.requiresConfiguration, isFalse); + }); + + test('secure web origin uses wss and the default port', () { + final server = ServerEndpoint.resolve( + base: Uri.parse('https://pipelines.example.test/runs'), + web: true, + ); + expect(server.uri, Uri.parse('wss://pipelines.example.test/connect')); + }); + + test('web never guesses an endpoint when the page is not HTTP(S)', () { + final server = ServerEndpoint.resolve( + base: Uri.parse('file:///tmp/index.html'), + web: true, + ); + expect(server.uri, isNull); + expect(server.error, contains('page URL')); + }); + + test('native requires an explicit endpoint instead of a baked host', () { + final server = ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: false, + ); + expect(server.uri, isNull); + expect(server.requiresConfiguration, isTrue); + expect(server.error, isNull); + }); + + test('native validates and normalizes the configured endpoint', () { + final server = ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: false, + configured: ' ws://192.168.1.20:8081 ', + ); + expect(server.uri, Uri.parse('ws://192.168.1.20:8081/connect')); + expect(server.requiresConfiguration, isFalse); + }); + + test('invalid native configuration reports the reason, never a fallback', () { + final server = ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: false, + configured: 'https://pipelines.example.test', + ); + expect(server.uri, isNull); + expect(server.error, contains('Unsupported scheme')); + }); +} diff --git a/app/test/features/runs/ui/run_detail_widget_test.dart b/app/test/features/runs/ui/run_detail_widget_test.dart index 4683db7e..972b0692 100644 --- a/app/test/features/runs/ui/run_detail_widget_test.dart +++ b/app/test/features/runs/ui/run_detail_widget_test.dart @@ -215,7 +215,7 @@ void main() { var backs = 0; await pumpDetail(tester, platform, controller, onBack: () => backs++); expect(find.textContaining('server unavailable'), findsOneWidget); - await tester.tap(find.text('Back to runs')); + await tester.tap(find.text('Back to list')); expect(backs, 1); }); diff --git a/app/test/features/runs/ui/runs_screen_test.dart b/app/test/features/runs/ui/runs_screen_test.dart new file mode 100644 index 00000000..e66cdfb8 --- /dev/null +++ b/app/test/features/runs/ui/runs_screen_test.dart @@ -0,0 +1,247 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; + +class _Gateway implements ApiGateway { + final framesController = StreamController.broadcast(); + final listRequests = >[]; + final detailRequests = >>{}; + + @override + Stream get frames => framesController.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final request = Completer(); + if (type == 'list_runs') { + listRequests.add(request); + } else if (type == 'get_run') { + final id = fields['run_id'] as num; + detailRequests.putIfAbsent(id, () => []).add(request); + } else { + request.completeError(UnsupportedError(type)); + } + return request.future; + } + + void replyList(int index, List runs) => + listRequests[index].complete({'runs': runs}); + + void replyDetail(num id, int index, JsonMap detail) => + detailRequests[id]![index].complete({'run_detail': detail}); + + void failDetail(num id, int index, Object error) => + detailRequests[id]![index].completeError(error); +} + +const _runs = [ + {'id': 1, 'title': 'Alpha run', 'name': 'alpha', 'status': 'running'}, + {'id': 2, 'title': 'Beta run', 'name': 'beta', 'status': 'failed'}, +]; + +Widget _materialScreen( + _Gateway gateway, { + int? initialRunId, + int syncToken = 0, + ValueChanged? onRunSelected, + VoidCallback? onBack, +}) => MaterialApp( + home: Scaffold( + body: RunsScreen( + gateway: gateway, + initialRunId: initialRunId, + syncToken: syncToken, + onRunSelected: onRunSelected, + onBack: onBack, + ), + ), +); + +Future _mountList(WidgetTester tester, _Gateway gateway) async { + await tester.pump(); + gateway.replyList(0, _runs); + await tester.pump(); + await tester.pump(); +} + +void main() { + late _Gateway gateway; + + setUp(() => gateway = _Gateway()); + tearDown(() => gateway.framesController.close()); + + testWidgets('initial run opens a pending detail with Back available', ( + tester, + ) async { + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 1)); + await _mountList(tester, gateway); + + expect(gateway.detailRequests[1], hasLength(1)); + expect(find.text('Loading run details…'), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + expect(find.text('Alpha run'), findsNothing); + + await tester.tap(find.text('Back to list')); + await tester.pump(); + expect(find.text('Alpha run'), findsOneWidget); + expect(find.text('Beta run'), findsOneWidget); + + // A reply that lands after Back must not reopen the previous detail. + gateway.replyDetail(1, 0, {'id': 1, 'title': 'Alpha run'}); + await tester.pump(); + expect(find.text('Alpha run'), findsOneWidget); + expect(find.text('Loading run details…'), findsNothing); + }); + + testWidgets('initial run renders its detail after the reply', (tester) async { + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 1)); + await _mountList(tester, gateway); + gateway.replyDetail(1, 0, { + 'id': 1, + 'title': 'Alpha run', + 'status': 'succeeded', + 'input': {'prompt': 'initial prompt'}, + }); + await tester.pump(); + + expect(find.text('Alpha run'), findsOneWidget); + expect(find.text('initial prompt'), findsOneWidget); + expect(find.text('Loading run details…'), findsNothing); + }); + + testWidgets('detail failure keeps Back and returns to the list', ( + tester, + ) async { + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 2)); + await _mountList(tester, gateway); + gateway.failDetail(2, 0, StateError('server unavailable')); + await tester.pump(); + + expect(find.textContaining('server unavailable'), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + + await tester.tap(find.text('Back to list')); + await tester.pump(); + expect(find.text('Alpha run'), findsOneWidget); + expect(find.textContaining('server unavailable'), findsNothing); + }); + + testWidgets('selecting a list row is driven by the controller selection', ( + tester, + ) async { + await tester.pumpWidget(_materialScreen(gateway)); + await _mountList(tester, gateway); + + await tester.tap(find.text('Beta run')); + await tester.pump(); + expect(gateway.detailRequests[2], hasLength(1)); + gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'}); + await tester.pump(); + expect(find.text('Beta run'), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + }); + + testWidgets('selection and Back report route changes to the host', ( + tester, + ) async { + int? selected; + var backs = 0; + await tester.pumpWidget( + _materialScreen( + gateway, + onRunSelected: (id) => selected = id, + onBack: () => backs++, + ), + ); + await _mountList(tester, gateway); + + await tester.tap(find.text('Beta run')); + await tester.pump(); + expect(selected, 2); + gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'}); + await tester.pump(); + + await tester.tap(find.text('Back to list')); + await tester.pump(); + expect(backs, 1); + expect(find.text('Alpha run'), findsOneWidget); + }); + + testWidgets('a route change opens and closes the named run', (tester) async { + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 2)); + await _mountList(tester, gateway); + expect(gateway.detailRequests[2], hasLength(1)); + gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'}); + await tester.pump(); + expect(find.text('Beta run'), findsOneWidget); + + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 1)); + await tester.pump(); + expect(gateway.detailRequests[1], hasLength(1)); + gateway.replyDetail(1, 0, {'id': 1, 'title': 'Alpha run'}); + await tester.pump(); + expect(find.text('Alpha run'), findsOneWidget); + + await tester.pumpWidget(_materialScreen(gateway)); + await tester.pump(); + expect(find.text('Alpha run'), findsOneWidget); + expect(find.text('Beta run'), findsOneWidget); + expect(find.text('Back to list'), findsNothing); + }); + + testWidgets('a reconnect token refreshes the open detail in place', ( + tester, + ) async { + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 2)); + await _mountList(tester, gateway); + gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'}); + await tester.pump(); + expect(find.text('Beta run'), findsOneWidget); + + await tester.pumpWidget( + _materialScreen(gateway, initialRunId: 2, syncToken: 1), + ); + await tester.pump(); + expect(gateway.listRequests, hasLength(2)); + gateway.replyList(1, _runs); + await tester.pump(); + await tester.pump(); + expect(gateway.detailRequests[2], hasLength(2)); + gateway.replyDetail(2, 1, { + 'id': 2, + 'title': 'Beta run', + 'status': 'succeeded', + }); + await tester.pump(); + expect(find.text('Beta run'), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + }); + + testWidgets( + 'Cupertino host keeps exactly one navigation bar while pending', + (tester) async { + await tester.pumpWidget( + CupertinoApp( + home: CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Runs')), + child: SafeArea( + child: RunsScreen(gateway: gateway, initialRunId: 1), + ), + ), + ), + ); + await _mountList(tester, gateway); + + expect(find.byType(CupertinoPageScaffold), findsOneWidget); + expect(find.byType(CupertinoNavigationBar), findsOneWidget); + expect(find.text('Loading run details…'), findsOneWidget); + expect(find.byType(CupertinoActivityIndicator), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); +} diff --git a/app/tool/runs_probe.mjs b/app/tool/runs_probe.mjs new file mode 100644 index 00000000..90088254 --- /dev/null +++ b/app/tool/runs_probe.mjs @@ -0,0 +1,423 @@ +import { spawn, execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'; +import { once } from 'node:events'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; + +import { startFixture } from './runs_probe_server.mjs'; + +// Browser acceptance for the Runs destination. +// +// Build one of the bundles first, then run from app/: +// flutter build web +// flutter build web --target=tool/runs_probe_entry.dart -o build/probe_web +// OPENCODE_ARTIFACT_DIR= node tool/runs_probe.mjs build/web +// +// Requires Google Chrome and Tesseract (OCR assertions cover canvas-rendered +// selectable text that Flutter web does not expose through semantics). +const output = process.env.OPENCODE_ARTIFACT_DIR; +if (!output) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(output, { recursive: true }); + +const root = resolve(process.argv[2] ?? 'build/probe_web'); +const fixture = await startFixture({ root }); + +const html = await fetch(`${fixture.url}/`); +const mime = html.headers.get('content-type') ?? ''; +if (html.status !== 200 || !mime.startsWith('text/html')) { + throw new Error(`Fixture index must be HTML: ${html.status} ${mime}`); +} +await html.text(); + +const profile = await mkdtemp(join(tmpdir(), 'i1-runs-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; }); + +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?.includes('detached') || message.method?.includes('crashed')) { + console.error('CDP event', JSON.stringify(message)); + } + if (message.method === 'Runtime.exceptionThrown') { + console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails)); + } + if (message.method === 'Log.entryAdded') { + console.error('PAGE LOG', JSON.stringify(message.params?.entry)); + } + if (message.method === 'Runtime.consoleAPICalled') { + console.error('PAGE CONSOLE', JSON.stringify(message.params)); + } + 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('Log.enable', {}, 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 enableSemantics = async () => { + await waitFor( + () => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), + 'Flutter semantics placeholder', + ); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(600); + }; + + const navigation = await send('Page.navigate', { url: `${fixture.url}/` }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await enableSemantics(); + await waitFor( + async () => (await evaluate('location.pathname')) === '/pipelines', + 'boot route correction to /pipelines', + ); + + const semanticText = () => evaluate(`(() => { + const chunks = []; + for (const el of document.querySelectorAll('flt-semantics')) { + const label = el.getAttribute('aria-label'); + if (label) chunks.push(label); + const value = el.getAttribute('aria-valuetext'); + if (value) chunks.push(value); + if (el.value) chunks.push(String(el.value)); + if (!el.children.length && el.innerText) chunks.push(el.innerText); + } + for (const el of document.querySelectorAll('input, textarea')) { + 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) { + const textNow = await semanticText(); + let extra = ''; + if (process.env.PROBE_DEBUG) { + extra = `\nNodes: ${JSON.stringify(await evaluate(`[...document.querySelectorAll('flt-semantics, input, textarea')] + .map((el) => ({ tag: el.tagName, role: el.getAttribute('role'), label: el.getAttribute('aria-label'), value: el.getAttribute('aria-valuetext') ?? el.value, text: el.innerText })) + .filter((item) => item.label || item.value || item.text)`))}`; + } + throw new Error(`${error.message}\nBody now:\n${textNow.slice(0, 3000)}${extra}`); + } + }; + + const clickText = async (text, { contains = false } = {}) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(text)}; + const candidates = [...document.querySelectorAll('flt-semantics')].filter((el) => { + const label = (el.getAttribute('aria-label') || el.innerText || '').trim(); + return label === wanted || (${contains} && label.includes(wanted)); + }); + const interactive = candidates.find((el) => + ['button', 'tab', 'link', 'checkbox', 'menuitem'].includes(el.getAttribute('role')), + ); + const target = interactive ?? candidates[0]; + if (!target) return false; + target.click(); + return true; + })()`); + if (!clicked) { + const labels = await evaluate(`[...document.querySelectorAll('flt-semantics')] + .map((el) => (el.getAttribute('aria-label') || '').trim()).filter(Boolean)`); + throw new Error(`Could not click ${JSON.stringify(text)}. Labels: ${JSON.stringify(labels)}`); + } + await delay(300); + }; + + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; + const path = join(output, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + return path; + }; + + const ocr = async (path) => { + const { stdout } = await promisify(execFile)('tesseract', [path, 'stdout']); + return stdout; + }; + + const assertOcr = async (path, text) => { + const read = await ocr(path); + if (!read.toLowerCase().includes(text.toLowerCase())) { + throw new Error(`OCR of ${path} lacks ${JSON.stringify(text)}:\n${read.slice(0, 3000)}`); + } + }; + + const wheel = (deltaY) => send('Input.dispatchMouseEvent', { + type: 'mouseWheel', + x: 195, + y: 500, + deltaX: 0, + deltaY, + }, session); + + const scrollUntil = async (text) => { + for (let attempt = 0; attempt < 20; attempt++) { + if ((await semanticText()).includes(text)) return; + await wheel(400); + await delay(180); + } + throw new Error(`Could not scroll to ${JSON.stringify(text)}`); + }; + + const setSize = async (width, height) => { + await send('Emulation.setDeviceMetricsOverride', { + width, + height, + deviceScaleFactor: 1, + mobile: width < 600, + }, session); + await delay(500); + }; + + await setSize(390, 844); + await clickText('Runs'); + if ((await evaluate('location.pathname')) !== '/runs') { + throw new Error(`Runs tab did not update the URL: ${await evaluate('location.pathname')}`); + } + await assertBody('Fixture live run'); + await assertBody('Fixture pending run'); + await assertBody('Fixture failing run'); + const captures = [await capture('i1-runs-phone-list')]; + await assertOcr(captures[0], 'Fixture live run'); + + await setSize(1280, 800); + await assertBody('Fixture live run'); + captures.push(await capture('i1-runs-desktop-list')); + await assertOcr(captures[1], 'Fixture live run'); + await setSize(390, 844); + + const live = await fetch(`${fixture.url}/fixture/live`, { method: 'POST' }); + if (!live.ok) throw new Error(`Fixture live trigger failed: ${live.status}`); + await assertBody('succeeded'); + captures.push(await capture('i1-runs-phone-list-live')); + await assertOcr(captures[2], 'succeeded'); + + await clickText('Fixture pending run', { contains: true }); + await assertBody('Loading run details…'); + await assertBody('Back to list'); + captures.push(await capture('i1-runs-phone-pending')); + await assertOcr(captures[3], 'Loading run details'); + await clickText('Back to list', { contains: true }); + await assertBody('Fixture failing run'); + + await clickText('Fixture failing run', { contains: true }); + await assertBody('Fixture detail failure: run 3 is unavailable'); + await assertBody('Back to list'); + captures.push(await capture('i1-runs-phone-error')); + await assertOcr(captures[4], 'run 3 is unavailable'); + await clickText('Back to list', { contains: true }); + await assertBody('Fixture live run'); + + await clickText('Fixture live run', { contains: true }); + if ((await evaluate('location.pathname')) !== '/runs/1') { + throw new Error(`Run selection did not update the URL: ${await evaluate('location.pathname')}`); + } + await assertBody('Original prompt'); + await assertBody('Timeline'); + await assertBody('build · visit 3'); + captures.push(await capture('i1-runs-phone-detail')); + await assertOcr(captures[5], 'fixture prompt with spaces'); + + await setSize(1280, 800); + await assertBody('Original prompt'); + captures.push(await capture('i1-runs-desktop-detail')); + await assertOcr(captures[6], 'fixture prompt with spaces'); + await setSize(390, 844); + + await clickText('Input'); + await wheel(250); + await delay(300); + captures.push(await capture('i1-runs-phone-detail-input')); + await assertOcr(captures[7], 'input payload'); + + await scrollUntil('Output'); + await clickText('Output'); + await wheel(250); + await delay(300); + captures.push(await capture('i1-runs-phone-detail-output')); + await assertOcr(captures[8], 'answer'); + + await scrollUntil('Metrics'); + await clickText('Metrics'); + await wheel(300); + await delay(300); + captures.push(await capture('i1-runs-phone-detail-metrics')); + await assertOcr(captures[9], 'Total tokens'); + await assertOcr(captures[9], 'Reported cost'); + + // Browser Back/Forward move between the in-app routes, not out of the app. + const path = () => evaluate('location.pathname'); + await evaluate('history.back()'); + await waitFor( + async () => (await path()) === '/runs', + 'browser Back to /runs', + ); + await waitFor( + async () => (await semanticText()).includes('Fixture live run'), + 'browser Back to the runs list', + ); + await waitFor( + async () => (await semanticText()).includes('Fixture live run'), + 'browser Back to the runs list', + ); + captures.push(await capture('i1-runs-phone-browser-back-list')); + await assertOcr(captures[10], 'Fixture live run'); + + await evaluate('history.forward()'); + await waitFor( + async () => (await path()) === '/runs/1' && (await semanticText()).includes('Original prompt'), + 'browser Forward to /runs/1', + ); + captures.push(await capture('i1-runs-phone-browser-forward-detail')); + + // A direct /runs/1 load is a real deep link: the detail opens and the URL stays. + await send('Page.navigate', { url: `${fixture.url}/runs/1` }, session); + await enableSemantics(); + await assertBody('Original prompt'); + if ((await path()) !== '/runs/1') throw new Error(`Deep link moved to ${await path()}`); + captures.push(await capture('i1-deeplink-run-1-phone')); + + // A drop keeps the open detail, reports reconnecting rather than unavailable, + // and has no raw transport exception anywhere on the page. + const beforeDrop = await (await fetch(`${fixture.url}/fixture/state`)).json(); + const refused = await fetch(`${fixture.url}/fixture/refuse`, { method: 'POST' }); + if (!refused.ok) throw new Error(`Fixture refuse failed: ${refused.status}`); + await assertBody('Reconnecting to Pipelines…'); + const duringDrop = await semanticText(); + for (const raw of ['WebSocketException', 'WebSocketChannelException', 'Failed to connect']) { + if (duringDrop.includes(raw)) throw new Error(`Raw transport text shown: ${raw}`); + } + if ((await path()) !== '/runs/1') throw new Error(`Drop moved the URL to ${await path()}`); + captures.push(await capture('i1-reconnect-detail-retained-phone')); + await assertOcr(captures[13], 'Original prompt'); + + // Accepting again plus Retry restores the same detail without a remount. + const accepted = await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' }); + if (!accepted.ok) throw new Error(`Fixture accept failed: ${accepted.status}`); + await clickText('Retry'); + await waitFor( + async () => + !(await semanticText()).includes('Reconnecting to Pipelines…') && + (await semanticText()).includes('Original prompt'), + 'detail restored after reconnect', + ); + if ((await path()) !== '/runs/1') throw new Error(`Reconnect moved the URL to ${await path()}`); + captures.push(await capture('i1-reconnect-detail-restored-phone')); + + // A first connection while the server refuses upgrades is friendly: the gate + // never prints the transport exception and does not flicker to "connecting". + await fetch(`${fixture.url}/fixture/refuse`, { method: 'POST' }); + await send('Page.navigate', { url: `${fixture.url}/runs` }, session); + await enableSemantics(); + await assertBody('Pipelines server unavailable'); + const gate = await semanticText(); + for (const raw of ['WebSocketException', 'WebSocketChannelException', 'Failed to connect']) { + if (gate.includes(raw)) throw new Error(`Gate printed raw transport text: ${raw}`); + } + captures.push(await capture('i1-gate-unavailable-friendly-phone')); + await delay(1500); + if (!(await semanticText()).includes('Pipelines server unavailable')) { + throw new Error('Gate left the unavailable state while retrying'); + } + await assertOcr(captures[15], 'Pipelines server unavailable'); + + await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' }); + await clickText('Retry'); + await assertBody('Fixture live run'); + captures.push(await capture('i1-gate-recovered-list-phone')); + + // Material host: the same deep link and route must render standard Material + // controls (the Cupertino host was selected by the macOS browser above). + await send( + 'Emulation.setUserAgentOverride', + { + userAgent: + 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' + + '(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36', + platform: 'Linux x86_64', + }, + session, + ); + await send('Page.navigate', { url: `${fixture.url}/runs/1` }, session); + await enableSemantics(); + await assertBody('Original prompt'); + await assertBody('Back to list'); + if ((await path()) !== '/runs/1') { + throw new Error(`Material deep link moved to ${await path()}`); + } + captures.push(await capture('i1-material-deeplink-run-1-phone')); + + const fixtureState = await (await fetch(`${fixture.url}/fixture/state`)).json(); + if (fixtureState.subscribed < 2) throw new Error(`App never resubscribed: ${JSON.stringify(fixtureState)}`); + if (fixtureState.listRuns < 2) throw new Error(`App never reloaded: ${JSON.stringify(fixtureState)}`); + if (fixtureState.getRun < 2) throw new Error(`Detail was not rehydrated: ${JSON.stringify(fixtureState)}`); + if (fixtureState.dropped < 1) throw new Error(`Fixture never dropped: ${JSON.stringify(fixtureState)}`); + console.log(JSON.stringify({ + ok: true, + fixture: fixture.url, + subscribed: fixtureState.subscribed, + listRuns: fixtureState.listRuns, + getRun: fixtureState.getRun, + dropped: fixtureState.dropped, + live: fixtureState.live, + 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 }); +} + +async function waitFor(check, label, attempts = 160) { + for (let attempt = 0; attempt < attempts; attempt++) { + const value = await check(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${label}`); +} diff --git a/app/tool/runs_probe_entry.dart b/app/tool/runs_probe_entry.dart new file mode 100644 index 00000000..332c62e9 --- /dev/null +++ b/app/tool/runs_probe_entry.dart @@ -0,0 +1,8 @@ +import 'package:pipelines_app/application/bootstrap.dart'; + +/// Browser acceptance entrypoint. +/// +/// This is intentionally the same composition as `lib/main.dart`; the +/// deterministic list/detail/error/live behavior comes from the isolated +/// websocket fixture that serves this bundle, not from app-side fake data. +void main() => runPipelinesApp(); diff --git a/app/tool/runs_probe_server.mjs b/app/tool/runs_probe_server.mjs new file mode 100644 index 00000000..b3093551 --- /dev/null +++ b/app/tool/runs_probe_server.mjs @@ -0,0 +1,410 @@ +import { createHash } from 'node:crypto'; +import { createServer } from 'node:http'; +import { readFile, realpath, stat } from 'node:fs/promises'; +import { extname, join, resolve, sep } from 'node:path'; +import { once } from 'node:events'; + +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', + '.css': 'text/css; charset=utf-8', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', +}; + +const RUNS = [ + { + id: 1, + title: 'Fixture live run', + name: 'fixture-live', + status: 'running', + created_at: '2026-10-21T12:00:00Z', + pipeline_id: 10, + }, + { + id: 2, + title: 'Fixture pending run', + name: 'fixture-pending', + status: 'running', + created_at: '2026-10-21T11:00:00Z', + pipeline_id: 10, + }, + { + id: 3, + title: 'Fixture failing run', + name: 'fixture-failing', + status: 'failed', + created_at: '2026-10-21T10:00:00Z', + pipeline_id: 10, + }, +]; + +const LIVE_EVENT = { + type: 'run_event', + run_id: 1, + status: 'succeeded', + outcome: 'success', + completed_steps: 2, + current_stage: 'test', + finished_at: '2026-10-21T12:05:00Z', +}; + +function detail(id, live) { + const status = id === 1 && live ? 'succeeded' : id === 3 ? 'failed' : 'running'; + return { + id, + title: RUNS.find((run) => run.id === id)?.title ?? `Run ${id}`, + name: 'fixture-pipeline', + status, + input: { + prompt: ' fixture prompt with spaces ', + note: 'input payload', + }, + output: { answer: 42, nested: { ok: true } }, + usage: { + stages: 2, + tokens_total: 120, + tokens_known_stages: 2, + tokens_in: 70, + tokens_out: 50, + split_known: true, + cost_known_stages: 2, + cost_usd: 0.25, + }, + steps: [ + { + stage: 'build', + sequence: 3, + status: 'completed', + outcome: 'success', + target: '#success', + }, + { + stage: 'test', + sequence: 4, + status: status === 'failed' ? 'failed' : 'completed', + outcome: status === 'failed' ? 'failure' : 'success', + target: status === 'failed' ? '#failure' : '#success', + }, + ], + }; +} + +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'); + } +} + +/** + * A deterministic, isolated Pipelines protocol fixture for the browser probe. + * It serves the built probe bundle and upgrades /connect on the same origin, so + * the normal web composition infers this server from Uri.base. + */ +export async function startFixture({ root }) { + const base = await realpath(root); + const connections = new Set(); + const sockets = new Set(); + let subscribed = 0; + let live = false; + let refuse = false; + let dropped = 0; + let listRuns = 0; + let getRun = 0; + + const dropConnections = () => { + for (const connection of connections) connection.close(); + connections.clear(); + dropped++; + }; + + const broadcast = (value) => { + for (const connection of connections) connection.send(value); + }; + + const server = createServer(async (req, res) => { + const pathname = new URL(req.url, 'http://fixture').pathname; + if (pathname === '/fixture/live' && req.method === 'POST') { + live = true; + broadcast(LIVE_EVENT); + res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); + return; + } + if (pathname === '/fixture/drop' && req.method === 'POST') { + dropConnections(); + res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); + return; + } + if (pathname === '/fixture/refuse' && req.method === 'POST') { + refuse = true; + dropConnections(); + res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); + return; + } + if (pathname === '/fixture/accept' && req.method === 'POST') { + refuse = false; + res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); + return; + } + if (pathname === '/fixture/state') { + res + .writeHead(200, { 'content-type': 'application/json' }) + .end(JSON.stringify({ + subscribed, + live, + connections: connections.size, + refuse, + dropped, + listRuns, + getRun, + })); + 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) => { + if (refuse) { + socket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n'); + return; + } + 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') { + // The real server may not acknowledge `subscribe`; keep it silent so + // the app's send-only path is exercised. + subscribed++; + return; + } + if (request.type === 'unsubscribe') return; + if (request.type === 'list_runs') { + listRuns++; + client.send({ id: request.id, type: 'runs', runs: RUNS, usage: null }); + return; + } + if (request.type === 'get_run') { + getRun++; + const id = request.run_id; + if (id === 2) { + // Deliberately slow so the browser sees the pending/Back state; + // it must still answer so the serialized request queue continues. + setTimeout(() => { + client.send({ id: request.id, type: 'run', run_detail: detail(2, live) }); + }, 2500); + return; + } + if (id === 3) { + client.send({ + id: request.id, + type: 'error', + error: 'Fixture detail failure: run 3 is unavailable', + }); + return; + } + client.send({ id: request.id, type: 'run', run_detail: detail(id, live) }); + return; + } + client.send({ + id: request.id, + type: 'error', + error: `Fixture does not implement ${request.type}`, + }); + }, + }); + connections.add(connection); + socket.on('data', (chunk) => connection.push(chunk)); + socket.on('close', () => connections.delete(connection)); + 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, + port, + url: `http://127.0.0.1:${port}`, + get subscribed() { + return subscribed; + }, + close: () => + new Promise((resolveClose) => { + for (const connection of connections) connection.close(); + server.close(() => resolveClose()); + for (const socket of sockets) socket.destroy(); + }), + }; +}