merge(app): finish retained Runs integration after deadline
This commit is contained in:
@@ -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<Object> this.routerConfig,
|
||||||
|
this.cupertino,
|
||||||
|
}) : destinationBodies = const {},
|
||||||
|
destination = null,
|
||||||
|
onDestinationSelected = null;
|
||||||
|
|
||||||
|
final Map<AppDestination, WidgetBuilder> destinationBodies;
|
||||||
|
final bool? cupertino;
|
||||||
|
final AppDestination? destination;
|
||||||
|
final ValueChanged<AppDestination>? onDestinationSelected;
|
||||||
|
final RouterConfig<Object>? 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;
|
||||||
|
}
|
||||||
@@ -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 = <String>[];
|
||||||
|
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);
|
||||||
|
}
|
||||||
@@ -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<AppRoute> {
|
||||||
|
const AppRouteParser();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<AppRoute> 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<AppRoute> 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<NavigatorState>();
|
||||||
|
static const _pageKey = ValueKey<String>('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<void>(key: _pageKey, child: child)
|
||||||
|
else
|
||||||
|
MaterialPage<void>(key: _pageKey, child: child),
|
||||||
|
],
|
||||||
|
onDidRemovePage: (_) {},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> setInitialRoutePath(AppRoute configuration) async {
|
||||||
|
_route = configuration;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> setNewRoutePath(AppRoute configuration) async {
|
||||||
|
if (configuration == _route) return;
|
||||||
|
_route = configuration;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> 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));
|
||||||
|
}
|
||||||
@@ -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<ConnectionState> _states;
|
||||||
|
late final StreamSubscription<JsonMap> _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<void> 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<void> 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<void> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
void useAppUrlStrategy() {}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import 'package:flutter_web_plugins/url_strategy.dart';
|
||||||
|
|
||||||
|
void useAppUrlStrategy() => usePathUrlStrategy();
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
@@ -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<PipelinesApp> createState() => _PipelinesAppState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PipelinesAppState extends State<PipelinesApp> {
|
||||||
|
late final AppSession _session;
|
||||||
|
late final AppRouterDelegate _delegate;
|
||||||
|
late final RouteInformationProvider _provider;
|
||||||
|
late final bool _ownsProvider;
|
||||||
|
late final RouterConfig<AppRoute> _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<AppRoute>(
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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<int>? 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')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,11 @@ const runStates = [
|
|||||||
'interrupted',
|
'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) {
|
({String label, String? pipeline}) runIdentity(dynamic title, dynamic name) {
|
||||||
final stored = '${title ?? ''}'.trim();
|
final stored = '${title ?? ''}'.trim();
|
||||||
return (
|
return (
|
||||||
@@ -116,25 +121,22 @@ List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
|
|||||||
int primary;
|
int primary;
|
||||||
switch (sort) {
|
switch (sort) {
|
||||||
case 'oldest_first':
|
case 'oldest_first':
|
||||||
primary = cmp(at ?? 0x7fffffffffffffff, bt ?? 0x7fffffffffffffff);
|
primary = cmp(at ?? _maxMillis, bt ?? _maxMillis);
|
||||||
break;
|
break;
|
||||||
case 'longest_duration':
|
case 'longest_duration':
|
||||||
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
|
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(duration(b) ?? -1, duration(a) ?? -1);
|
||||||
if (primary == 0) {
|
if (primary == 0) {
|
||||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 'shortest_duration':
|
case 'shortest_duration':
|
||||||
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
|
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
|
||||||
if (primary == 0) {
|
if (primary == 0) {
|
||||||
primary = cmp(
|
primary = cmp(duration(a) ?? _maxMillis, duration(b) ?? _maxMillis);
|
||||||
duration(a) ?? 0x7fffffffffffffff,
|
|
||||||
duration(b) ?? 0x7fffffffffffffff,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (primary == 0) {
|
if (primary == 0) {
|
||||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 'pipeline_name':
|
case 'pipeline_name':
|
||||||
@@ -142,7 +144,7 @@ List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
|
|||||||
'${b['name'] ?? ''}'.toLowerCase(),
|
'${b['name'] ?? ''}'.toLowerCase(),
|
||||||
);
|
);
|
||||||
if (primary == 0) {
|
if (primary == 0) {
|
||||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 'status':
|
case 'status':
|
||||||
@@ -150,11 +152,11 @@ List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
|
|||||||
'${b['status'] ?? ''}'.toLowerCase(),
|
'${b['status'] ?? ''}'.toLowerCase(),
|
||||||
);
|
);
|
||||||
if (primary == 0) {
|
if (primary == 0) {
|
||||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||||
}
|
}
|
||||||
return primary == 0
|
return primary == 0
|
||||||
? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0)
|
? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0)
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
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';
|
||||||
|
|
||||||
|
/// 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,
|
||||||
|
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<int>? onRunSelected;
|
||||||
|
final VoidCallback? onBack;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<RunsScreen> createState() => _RunsScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RunsScreenState extends State<RunsScreen> {
|
||||||
|
late final RunsController controller;
|
||||||
|
num? _shownRunId;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
controller = RunsController(RunsRepository(widget.gateway));
|
||||||
|
controller.listen(widget.gateway.frames);
|
||||||
|
controller.addListener(_selectionChanged);
|
||||||
|
controller.load(widget.initialRunId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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(_selectionChanged);
|
||||||
|
controller.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final selected = controller.selectedRunId != null;
|
||||||
|
return Stack(
|
||||||
|
children: [
|
||||||
|
AnimatedBuilder(
|
||||||
|
animation: controller,
|
||||||
|
builder: (context, _) => Offstage(
|
||||||
|
offstage: selected,
|
||||||
|
child: RunsList(controller: controller, onSelected: _select),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (selected) RunDetailView(controller: controller, onBack: _back),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import '../../../core/api_gateway.dart';
|
||||||
|
import '../domain/run_models.dart';
|
||||||
|
|
||||||
|
/// One labelled value in the run detail's metrics block.
|
||||||
|
typedef DetailMetric = ({String label, String value});
|
||||||
|
|
||||||
|
/// One recorded visit in the run detail's timeline.
|
||||||
|
typedef DetailVisit = ({String title, String subtitle});
|
||||||
|
|
||||||
|
/// The run's primary label: the stored title, else the pipeline name, and only
|
||||||
|
/// then the numeric identity.
|
||||||
|
String detailTitle(JsonMap run) {
|
||||||
|
final identity = runIdentity(run['title'], run['name']);
|
||||||
|
return identity.label.trim().isEmpty ? 'Run ${run['id']}' : identity.label;
|
||||||
|
}
|
||||||
|
|
||||||
|
String detailPipeline(JsonMap run) {
|
||||||
|
final name = '${run['name'] ?? ''}'.trim();
|
||||||
|
return name.isEmpty ? 'unavailable' : name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The original prompt exactly as the server stored it; never trimmed or
|
||||||
|
/// replaced by another field.
|
||||||
|
String? detailPrompt(JsonMap run) {
|
||||||
|
final input = run['input'];
|
||||||
|
return input is Map && input['prompt'] is String
|
||||||
|
? input['prompt'] as String
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Nested input/output shown as formatted, selectable JSON.
|
||||||
|
String detailJson(dynamic value) =>
|
||||||
|
const JsonEncoder.withIndent(' ').convert(value);
|
||||||
|
|
||||||
|
bool detailEmpty(dynamic value) => value is! Map || value.isEmpty;
|
||||||
|
|
||||||
|
/// Reported run metrics. A present zero with a reporting stage count is a real
|
||||||
|
/// zero; a zero without that evidence is unavailable, never a measured zero.
|
||||||
|
List<DetailMetric> detailUsageMetrics(dynamic raw) {
|
||||||
|
if (raw is! Map || raw.isEmpty) return const [];
|
||||||
|
final usage = Map<String, dynamic>.from(raw);
|
||||||
|
final stages = _int(usage['stages']);
|
||||||
|
final tokenStages = _int(usage['tokens_known_stages']) ?? 0;
|
||||||
|
final costStages = _int(usage['cost_known_stages']) ?? 0;
|
||||||
|
final totalTokens = _int(usage['tokens_total']);
|
||||||
|
final splitKnown = usage['split_known'] == true && tokenStages > 0;
|
||||||
|
final rows = <DetailMetric>[
|
||||||
|
if (stages != null) (label: 'Stages', value: '$stages'),
|
||||||
|
(
|
||||||
|
label: 'Total tokens',
|
||||||
|
value: tokenStages == 0 || totalTokens == null
|
||||||
|
? 'Unavailable'
|
||||||
|
: '$totalTokens',
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: 'Input tokens',
|
||||||
|
value: splitKnown ? '${_int(usage['tokens_in']) ?? 0}' : 'Unavailable',
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: 'Output tokens',
|
||||||
|
value: splitKnown ? '${_int(usage['tokens_out']) ?? 0}' : 'Unavailable',
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: 'Reported cost',
|
||||||
|
// cost_usd is omitted by the server when zero, so a known stage count
|
||||||
|
// makes an absent value a real $0.000000 rather than an unknown cost.
|
||||||
|
value: costStages == 0
|
||||||
|
? 'Unavailable'
|
||||||
|
: '\$${((usage['cost_usd'] as num?) ?? 0).toStringAsFixed(6)}',
|
||||||
|
),
|
||||||
|
];
|
||||||
|
if (stages != null && tokenStages < stages) {
|
||||||
|
rows.add((
|
||||||
|
label: 'Token reporting',
|
||||||
|
value: '$tokenStages of $stages stages',
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if (stages != null && costStages < stages) {
|
||||||
|
rows.add((label: 'Cost reporting', value: '$costStages of $stages stages'));
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every recorded visit with its server sequence, in recorded order.
|
||||||
|
List<DetailVisit> detailTimeline(dynamic steps) {
|
||||||
|
if (steps is! List) return const [];
|
||||||
|
return [
|
||||||
|
for (final step in steps.whereType<Map>())
|
||||||
|
(
|
||||||
|
title:
|
||||||
|
'${_text(step['stage'], 'Stage unavailable')} · visit '
|
||||||
|
'${step['sequence'] is num ? (step['sequence'] as num).toInt() : 'unavailable'}',
|
||||||
|
subtitle: _visitSubtitle(step),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
String _visitSubtitle(Map step) {
|
||||||
|
final status = _text(step['status'], 'Status unavailable');
|
||||||
|
final outcome = '${step['outcome'] ?? ''}'.trim();
|
||||||
|
final target = '${step['target'] ?? ''}'.trim();
|
||||||
|
return [
|
||||||
|
status,
|
||||||
|
if (outcome.isNotEmpty) outcome,
|
||||||
|
if (target.isNotEmpty) '→ $target',
|
||||||
|
].join(' · ');
|
||||||
|
}
|
||||||
|
|
||||||
|
String _text(dynamic value, String fallback) {
|
||||||
|
final text = '${value ?? ''}'.trim();
|
||||||
|
return text.isEmpty ? fallback : text;
|
||||||
|
}
|
||||||
|
|
||||||
|
int? _int(dynamic value) => value is num ? value.toInt() : null;
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
import 'package:flutter/cupertino.dart';
|
||||||
|
|
||||||
|
import '../../../core/api_gateway.dart';
|
||||||
|
import '../domain/run_models.dart';
|
||||||
|
import 'run_detail_content.dart';
|
||||||
|
|
||||||
|
/// The runs detail with standard Cupertino controls. It has no Material
|
||||||
|
/// ancestor: sections use native Cupertino expansion tiles and grouped list
|
||||||
|
/// sections, and copy feedback is an inline live-region status.
|
||||||
|
Widget buildCupertinoRunDetail({
|
||||||
|
required BuildContext context,
|
||||||
|
required JsonMap run,
|
||||||
|
required bool detailLoading,
|
||||||
|
required String? error,
|
||||||
|
required bool copying,
|
||||||
|
required String? copyStatus,
|
||||||
|
required VoidCallback onBack,
|
||||||
|
required VoidCallback onCopy,
|
||||||
|
}) {
|
||||||
|
final theme = CupertinoTheme.of(context);
|
||||||
|
final prompt = detailPrompt(run);
|
||||||
|
final visits = detailTimeline(run['steps']);
|
||||||
|
final metrics = detailUsageMetrics(run['usage']);
|
||||||
|
return ListView(
|
||||||
|
key: ValueKey<String>('run-detail-${run['id']}'),
|
||||||
|
children: [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
CupertinoButton(
|
||||||
|
padding: EdgeInsets.zero,
|
||||||
|
onPressed: onBack,
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
const Icon(CupertinoIcons.back),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
const Text('Back'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
if (copying) const CupertinoActivityIndicator(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
detailTitle(run),
|
||||||
|
style: theme.textTheme.navLargeTitleTextStyle,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(runStatusLabel(run)),
|
||||||
|
Text('Run ${run['id']} · Pipeline ${detailPipeline(run)}'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (detailLoading) const _CupertinoNotice('Refreshing run details…'),
|
||||||
|
if (error != null) _CupertinoNotice(error),
|
||||||
|
if (prompt != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsetsDirectional.fromSTEB(16, 16, 16, 0),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Wrap(
|
||||||
|
alignment: WrapAlignment.spaceBetween,
|
||||||
|
crossAxisAlignment: WrapCrossAlignment.center,
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 4,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'Original prompt',
|
||||||
|
style: theme.textTheme.navTitleTextStyle,
|
||||||
|
),
|
||||||
|
CupertinoButton(
|
||||||
|
padding: EdgeInsets.zero,
|
||||||
|
onPressed: copying ? null : onCopy,
|
||||||
|
child: const Text('Copy prompt'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
_CupertinoSelectableText(prompt),
|
||||||
|
if (copyStatus != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 4),
|
||||||
|
child: Semantics(liveRegion: true, child: Text(copyStatus)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
_fieldSection('Input', run['input'], 'No input recorded.'),
|
||||||
|
_fieldSection('Output', run['output'], 'No output recorded.'),
|
||||||
|
CupertinoListSection.insetGrouped(
|
||||||
|
header: const Text('Timeline'),
|
||||||
|
children: [
|
||||||
|
if (visits.isEmpty)
|
||||||
|
const CupertinoListTile(title: Text('No visits recorded.'))
|
||||||
|
else
|
||||||
|
for (final visit in visits)
|
||||||
|
CupertinoListTile(
|
||||||
|
leading: const Icon(CupertinoIcons.circle),
|
||||||
|
title: Text(visit.title),
|
||||||
|
subtitle: Text(visit.subtitle),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
CupertinoListSection.insetGrouped(
|
||||||
|
children: [
|
||||||
|
CupertinoExpansionTile(
|
||||||
|
title: const Text('Metrics'),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 16),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
if (metrics.isEmpty)
|
||||||
|
const Text('No reported usage.')
|
||||||
|
else
|
||||||
|
for (final metric in metrics)
|
||||||
|
CupertinoListTile(
|
||||||
|
title: Text(metric.label),
|
||||||
|
subtitle: Text(metric.value),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _fieldSection(String title, dynamic value, String empty) {
|
||||||
|
final text = detailEmpty(value) ? empty : detailJson(value);
|
||||||
|
return CupertinoListSection.insetGrouped(
|
||||||
|
children: [
|
||||||
|
CupertinoExpansionTile(
|
||||||
|
title: Text(title),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 16),
|
||||||
|
child: _CupertinoSelectableText(text),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _CupertinoNotice extends StatelessWidget {
|
||||||
|
const _CupertinoNotice(this.text);
|
||||||
|
final String text;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => Padding(
|
||||||
|
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
|
||||||
|
child: Semantics(liveRegion: true, child: Text(text)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A read-only Cupertino text control: plain, selectable text without a
|
||||||
|
/// Material dependency, while keeping native selection and copy affordances.
|
||||||
|
class _CupertinoSelectableText extends StatefulWidget {
|
||||||
|
const _CupertinoSelectableText(this.text);
|
||||||
|
final String text;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_CupertinoSelectableText> createState() =>
|
||||||
|
_CupertinoSelectableTextState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _CupertinoSelectableTextState extends State<_CupertinoSelectableText> {
|
||||||
|
late final TextEditingController _controller = TextEditingController(
|
||||||
|
text: widget.text,
|
||||||
|
);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didUpdateWidget(_CupertinoSelectableText oldWidget) {
|
||||||
|
super.didUpdateWidget(oldWidget);
|
||||||
|
if (widget.text != oldWidget.text) _controller.text = widget.text;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_controller.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => CupertinoTextField(
|
||||||
|
controller: _controller,
|
||||||
|
readOnly: true,
|
||||||
|
maxLines: null,
|
||||||
|
padding: EdgeInsets.zero,
|
||||||
|
decoration: const BoxDecoration(),
|
||||||
|
style: CupertinoTheme.of(context).textTheme.textStyle,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../../../core/api_gateway.dart';
|
||||||
|
import '../domain/run_models.dart';
|
||||||
|
import 'run_detail_content.dart';
|
||||||
|
|
||||||
|
/// The runs detail with standard Material controls.
|
||||||
|
Widget buildMaterialRunDetail({
|
||||||
|
required BuildContext context,
|
||||||
|
required JsonMap run,
|
||||||
|
required bool detailLoading,
|
||||||
|
required String? error,
|
||||||
|
required bool copying,
|
||||||
|
required String? copyStatus,
|
||||||
|
required VoidCallback onBack,
|
||||||
|
required VoidCallback onCopy,
|
||||||
|
}) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final prompt = detailPrompt(run);
|
||||||
|
final visits = detailTimeline(run['steps']);
|
||||||
|
final metrics = detailUsageMetrics(run['usage']);
|
||||||
|
return ListView(
|
||||||
|
key: ValueKey<String>('run-detail-${run['id']}'),
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
children: [
|
||||||
|
Align(
|
||||||
|
alignment: AlignmentDirectional.centerStart,
|
||||||
|
child: TextButton.icon(
|
||||||
|
onPressed: onBack,
|
||||||
|
icon: const Icon(Icons.arrow_back),
|
||||||
|
label: const Text('Back to list'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Text(detailTitle(run), style: theme.textTheme.headlineSmall),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 4,
|
||||||
|
crossAxisAlignment: WrapCrossAlignment.center,
|
||||||
|
children: [
|
||||||
|
Chip(label: Text(runStatusLabel(run))),
|
||||||
|
Text('Run ${run['id']}'),
|
||||||
|
Text('Pipeline ${detailPipeline(run)}'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
if (detailLoading) const _Notice('Refreshing run details…'),
|
||||||
|
if (error != null) _Notice(error),
|
||||||
|
if (prompt != null) ...[
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
'Original prompt',
|
||||||
|
style: theme.textTheme.titleMedium,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Copy prompt',
|
||||||
|
onPressed: copying ? null : onCopy,
|
||||||
|
icon: const Icon(Icons.copy),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
SelectableText(prompt),
|
||||||
|
if (copyStatus != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 4),
|
||||||
|
child: Semantics(liveRegion: true, child: Text(copyStatus)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
_fieldSection('Input', run['input'], 'No input recorded.'),
|
||||||
|
_fieldSection('Output', run['output'], 'No output recorded.'),
|
||||||
|
Text('Timeline', style: theme.textTheme.titleLarge),
|
||||||
|
if (visits.isEmpty)
|
||||||
|
const Text('No visits recorded.')
|
||||||
|
else
|
||||||
|
...visits.map(
|
||||||
|
(visit) => ListTile(
|
||||||
|
leading: const Icon(Icons.circle_outlined),
|
||||||
|
title: Text(visit.title),
|
||||||
|
subtitle: Text(visit.subtitle),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
ExpansionTile(
|
||||||
|
title: const Text('Metrics'),
|
||||||
|
children: [
|
||||||
|
if (metrics.isEmpty)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.all(16),
|
||||||
|
child: Text('No reported usage.'),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
...metrics.map(
|
||||||
|
(metric) => ListTile(
|
||||||
|
title: Text(metric.label),
|
||||||
|
subtitle: Text(metric.value),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _fieldSection(String title, dynamic value, String empty) {
|
||||||
|
final text = detailEmpty(value) ? empty : detailJson(value);
|
||||||
|
return ExpansionTile(
|
||||||
|
title: Text(title),
|
||||||
|
children: [
|
||||||
|
Padding(padding: const EdgeInsets.all(16), child: SelectableText(text)),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _Notice extends StatelessWidget {
|
||||||
|
const _Notice(this.text);
|
||||||
|
final String text;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||||
|
child: Semantics(liveRegion: true, child: Text(text)),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
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';
|
||||||
|
import 'runs_controller.dart';
|
||||||
|
|
||||||
|
class RunDetailView extends StatefulWidget {
|
||||||
|
const RunDetailView({
|
||||||
|
super.key,
|
||||||
|
required this.controller,
|
||||||
|
required this.onBack,
|
||||||
|
});
|
||||||
|
|
||||||
|
final RunsController controller;
|
||||||
|
final VoidCallback onBack;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<RunDetailView> createState() => _RunDetailViewState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RunDetailViewState extends State<RunDetailView> {
|
||||||
|
bool _copying = false;
|
||||||
|
String? _copyStatus;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => AnimatedBuilder(
|
||||||
|
animation: widget.controller,
|
||||||
|
builder: (context, _) {
|
||||||
|
final cupertino = usesCupertinoHost(context);
|
||||||
|
final run = widget.controller.detail;
|
||||||
|
if (run == null) return _placeholder(context, cupertino: cupertino);
|
||||||
|
final prompt = detailPrompt(run);
|
||||||
|
return cupertino
|
||||||
|
? buildCupertinoRunDetail(
|
||||||
|
context: context,
|
||||||
|
run: run,
|
||||||
|
detailLoading: widget.controller.detailLoading,
|
||||||
|
error: widget.controller.error,
|
||||||
|
copying: _copying,
|
||||||
|
copyStatus: _copyStatus,
|
||||||
|
onBack: widget.onBack,
|
||||||
|
onCopy: () => _copyPrompt(prompt ?? '', cupertino: true),
|
||||||
|
)
|
||||||
|
: buildMaterialRunDetail(
|
||||||
|
context: context,
|
||||||
|
run: run,
|
||||||
|
detailLoading: widget.controller.detailLoading,
|
||||||
|
error: widget.controller.error,
|
||||||
|
copying: _copying,
|
||||||
|
copyStatus: _copyStatus,
|
||||||
|
onBack: widget.onBack,
|
||||||
|
onCopy: () => _copyPrompt(prompt ?? '', cupertino: false),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
Widget _placeholder(BuildContext context, {required bool cupertino}) {
|
||||||
|
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),
|
||||||
|
],
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||||
|
child: Text(message, textAlign: TextAlign.center),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
if (cupertino)
|
||||||
|
CupertinoButton(
|
||||||
|
onPressed: widget.onBack,
|
||||||
|
child: const Text('Back to list'),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
FilledButton(
|
||||||
|
onPressed: widget.onBack,
|
||||||
|
child: const Text('Back to list'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copies the stored prompt byte-for-byte. A refusal is surfaced, never
|
||||||
|
/// replaced by copying a title or the formatted detail.
|
||||||
|
Future<void> _copyPrompt(String prompt, {required bool cupertino}) async {
|
||||||
|
if (_copying) return;
|
||||||
|
setState(() => _copying = true);
|
||||||
|
String message;
|
||||||
|
try {
|
||||||
|
await Clipboard.setData(ClipboardData(text: prompt));
|
||||||
|
message = 'Prompt copied to clipboard.';
|
||||||
|
} catch (_) {
|
||||||
|
message = 'Could not copy prompt to clipboard.';
|
||||||
|
}
|
||||||
|
if (!mounted) return;
|
||||||
|
final scaffold = cupertino ? null : Scaffold.maybeOf(context);
|
||||||
|
final inline = cupertino || scaffold == null;
|
||||||
|
setState(() {
|
||||||
|
_copying = false;
|
||||||
|
_copyStatus = inline ? message : null;
|
||||||
|
});
|
||||||
|
if (!cupertino && scaffold != null) {
|
||||||
|
ScaffoldMessenger.maybeOf(
|
||||||
|
context,
|
||||||
|
)?.showSnackBar(SnackBar(content: Text(message)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import '../../../core/api_gateway.dart';
|
||||||
|
import '../data/runs_repository.dart';
|
||||||
|
import '../domain/run_events.dart';
|
||||||
|
import '../domain/run_models.dart';
|
||||||
|
|
||||||
|
class RunsController extends ChangeNotifier {
|
||||||
|
RunsController(this.repository);
|
||||||
|
final RunsRepository repository;
|
||||||
|
StreamSubscription<JsonMap>? _subscription;
|
||||||
|
List<JsonMap> runs = [];
|
||||||
|
JsonMap? detail, usage;
|
||||||
|
String? error;
|
||||||
|
bool loading = false, detailLoading = false;
|
||||||
|
String query = '',
|
||||||
|
sort = 'newest_first',
|
||||||
|
scheduled = 'any',
|
||||||
|
timeRange = 'any_time';
|
||||||
|
final Set<String> statuses = {};
|
||||||
|
int? pipelineId;
|
||||||
|
// List and detail requests advance independent generations so neither can
|
||||||
|
// make the other's in-flight reply stale.
|
||||||
|
int _listGeneration = 0, _detailGeneration = 0;
|
||||||
|
num? _selectedId;
|
||||||
|
Timer? _detailRefresh;
|
||||||
|
bool _listResyncing = false, _listAgain = false;
|
||||||
|
bool _detailRefreshing = false, _detailAgain = false;
|
||||||
|
bool _disposed = false;
|
||||||
|
|
||||||
|
num? get selectedRunId => _selectedId;
|
||||||
|
|
||||||
|
void listen(Stream<JsonMap> frames) {
|
||||||
|
_subscription?.cancel();
|
||||||
|
_subscription = frames
|
||||||
|
.where((f) => f['type'] == 'run_event')
|
||||||
|
.listen(_event);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> load([int? initialId]) async {
|
||||||
|
final token = ++_listGeneration;
|
||||||
|
_listAgain = false;
|
||||||
|
loading = true;
|
||||||
|
error = null;
|
||||||
|
notifyListeners();
|
||||||
|
try {
|
||||||
|
final result = await repository.listRuns();
|
||||||
|
if (!_listOwned(token)) return;
|
||||||
|
runs = result.runs;
|
||||||
|
usage = result.usage;
|
||||||
|
} catch (e) {
|
||||||
|
if (!_listOwned(token)) return;
|
||||||
|
error = '$e';
|
||||||
|
}
|
||||||
|
if (!_listOwned(token)) return;
|
||||||
|
loading = false;
|
||||||
|
notifyListeners();
|
||||||
|
// A run event may have arrived while the list request was in flight; one
|
||||||
|
// resync after it keeps the pushed state without dropping the event.
|
||||||
|
_resyncAgainIfNeeded();
|
||||||
|
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<void> resync() async {
|
||||||
|
final selected = _selectedId;
|
||||||
|
await load();
|
||||||
|
if (selected != null && _selectedId == selected) await select(selected);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> select(num id) async {
|
||||||
|
final token = ++_detailGeneration;
|
||||||
|
_cancelDetailRefresh();
|
||||||
|
// Keep a same-run detail while it refreshes, but never present the previous
|
||||||
|
// run as if it were the newly selected one.
|
||||||
|
if (_selectedId != id) detail = null;
|
||||||
|
_selectedId = id;
|
||||||
|
detailLoading = true;
|
||||||
|
error = null;
|
||||||
|
notifyListeners();
|
||||||
|
try {
|
||||||
|
final value = await repository.getRun(id);
|
||||||
|
if (!_detailOwned(id, token)) return;
|
||||||
|
detail = value;
|
||||||
|
} catch (e) {
|
||||||
|
if (!_detailOwned(id, token)) return;
|
||||||
|
error = '$e';
|
||||||
|
}
|
||||||
|
if (!_detailOwned(id, token)) return;
|
||||||
|
detailLoading = false;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void back() {
|
||||||
|
++_detailGeneration;
|
||||||
|
_cancelDetailRefresh();
|
||||||
|
_selectedId = null;
|
||||||
|
detail = null;
|
||||||
|
detailLoading = false;
|
||||||
|
error = null;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void setQuery(String value) {
|
||||||
|
query = value;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void setStatus(String? value) {
|
||||||
|
if (value == null) {
|
||||||
|
statuses.clear();
|
||||||
|
} else if (!statuses.add(value)) {
|
||||||
|
statuses.remove(value);
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void setPipeline(int? value) {
|
||||||
|
pipelineId = value;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void setScheduled(String value) {
|
||||||
|
scheduled = value;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void setSort(String value) {
|
||||||
|
sort = value;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _event(JsonMap frame) {
|
||||||
|
final folded = foldRunEvent(runs, frame);
|
||||||
|
runs = folded.runs;
|
||||||
|
if (detail?['id'] == frame['run_id']) {
|
||||||
|
detail = foldRunEventDetail(detail, frame);
|
||||||
|
}
|
||||||
|
if (frame['run_id'] == null || folded.needsResync) {
|
||||||
|
_scheduleListRefresh();
|
||||||
|
}
|
||||||
|
final selected = _selectedId;
|
||||||
|
if (selected != null &&
|
||||||
|
frame['run_id'] == selected &&
|
||||||
|
(folded.needsResync || runDetailNeedsFullSync(frame))) {
|
||||||
|
_scheduleDetailRefresh(selected);
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _scheduleListRefresh() {
|
||||||
|
if (_disposed) return;
|
||||||
|
if (_listResyncing || loading) {
|
||||||
|
_listAgain = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_listResyncing = true;
|
||||||
|
loading = true;
|
||||||
|
notifyListeners();
|
||||||
|
unawaited(_reloadList());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _reloadList() async {
|
||||||
|
final token = ++_listGeneration;
|
||||||
|
_listAgain = false;
|
||||||
|
try {
|
||||||
|
final result = await repository.listRuns();
|
||||||
|
if (!_listOwned(token)) return;
|
||||||
|
runs = result.runs;
|
||||||
|
usage = result.usage;
|
||||||
|
error = null;
|
||||||
|
} catch (e) {
|
||||||
|
if (_listOwned(token)) error = '$e';
|
||||||
|
} finally {
|
||||||
|
_listResyncing = false;
|
||||||
|
if (_listOwned(token)) {
|
||||||
|
loading = false;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
// A followup may have been requested while this (possibly superseded)
|
||||||
|
// request was still the one marked in flight.
|
||||||
|
_resyncAgainIfNeeded();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _resyncAgainIfNeeded() {
|
||||||
|
if (_disposed || !_listAgain) return;
|
||||||
|
_listAgain = false;
|
||||||
|
_scheduleListRefresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _scheduleDetailRefresh(num id) {
|
||||||
|
if (_disposed || _selectedId != id) return;
|
||||||
|
if (_detailRefreshing) {
|
||||||
|
_detailAgain = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_detailRefresh?.cancel();
|
||||||
|
_detailRefresh = Timer(
|
||||||
|
const Duration(milliseconds: 150),
|
||||||
|
() => _refreshDetail(id, _detailGeneration),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _refreshDetail(num id, int token) async {
|
||||||
|
_detailRefresh = null;
|
||||||
|
if (!_detailOwned(id, token)) return;
|
||||||
|
_detailRefreshing = true;
|
||||||
|
try {
|
||||||
|
final value = await repository.getRun(id);
|
||||||
|
if (_detailOwned(id, token)) {
|
||||||
|
detail = value;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (_detailOwned(id, token)) {
|
||||||
|
error = '$e';
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (_detailOwned(id, token)) {
|
||||||
|
_detailRefreshing = false;
|
||||||
|
if (_detailAgain) {
|
||||||
|
_detailAgain = false;
|
||||||
|
unawaited(_refreshDetail(id, token));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _cancelDetailRefresh() {
|
||||||
|
_detailRefresh?.cancel();
|
||||||
|
_detailRefresh = null;
|
||||||
|
_detailAgain = false;
|
||||||
|
_detailRefreshing = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _listOwned(int token) => !_disposed && token == _listGeneration;
|
||||||
|
|
||||||
|
bool _detailOwned(num id, int token) =>
|
||||||
|
!_disposed && token == _detailGeneration && _selectedId == id;
|
||||||
|
|
||||||
|
List<JsonMap> get visibleRuns => sortRuns(
|
||||||
|
filterRuns(
|
||||||
|
runs,
|
||||||
|
statuses: statuses,
|
||||||
|
pipelineId: pipelineId,
|
||||||
|
scheduled: scheduled,
|
||||||
|
timeRange: timeRange,
|
||||||
|
)
|
||||||
|
.where(
|
||||||
|
(r) => '${r['title'] ?? r['name'] ?? ''}'.toLowerCase().contains(
|
||||||
|
query.toLowerCase(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.toList(),
|
||||||
|
sort: sort,
|
||||||
|
);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_disposed = true;
|
||||||
|
_subscription?.cancel();
|
||||||
|
_detailRefresh?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
import 'package:flutter/cupertino.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';
|
||||||
|
|
||||||
|
class RunsList extends StatelessWidget {
|
||||||
|
const RunsList({
|
||||||
|
super.key,
|
||||||
|
required this.controller,
|
||||||
|
required this.onSelected,
|
||||||
|
});
|
||||||
|
|
||||||
|
final RunsController controller;
|
||||||
|
final ValueChanged<num> onSelected;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
if (controller.loading && controller.runs.isEmpty) {
|
||||||
|
return Center(
|
||||||
|
child: usesCupertinoHost(context)
|
||||||
|
? const CupertinoActivityIndicator()
|
||||||
|
: const CircularProgressIndicator(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (controller.error != null && controller.runs.isEmpty) {
|
||||||
|
return _emptyError(context);
|
||||||
|
}
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
if (controller.usage != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||||
|
child: Text('Usage: ${controller.usage}'),
|
||||||
|
),
|
||||||
|
if (controller.error != null) _inlineError(context),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
child: usesCupertinoHost(context)
|
||||||
|
? CupertinoSearchTextField(
|
||||||
|
placeholder: 'Filter runs',
|
||||||
|
onChanged: controller.setQuery,
|
||||||
|
)
|
||||||
|
: TextField(
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Filter runs',
|
||||||
|
prefixIcon: Icon(Icons.search),
|
||||||
|
),
|
||||||
|
onChanged: controller.setQuery,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
_selectors(context),
|
||||||
|
Expanded(
|
||||||
|
child: controller.visibleRuns.isEmpty
|
||||||
|
? const Center(child: Text('No runs found.'))
|
||||||
|
: ListView.builder(
|
||||||
|
itemCount: controller.visibleRuns.length,
|
||||||
|
itemBuilder: (context, index) =>
|
||||||
|
_runTile(context, controller.visibleRuns[index]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _emptyError(BuildContext context) => Center(
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Text(controller.error!),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
usesCupertinoHost(context)
|
||||||
|
? CupertinoButton(
|
||||||
|
onPressed: controller.load,
|
||||||
|
child: const Text('Retry'),
|
||||||
|
)
|
||||||
|
: FilledButton(
|
||||||
|
onPressed: controller.load,
|
||||||
|
child: const Text('Retry'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
Widget _inlineError(BuildContext context) => Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Expanded(child: Text(controller.error!)),
|
||||||
|
if (usesCupertinoHost(context))
|
||||||
|
CupertinoButton(
|
||||||
|
onPressed: controller.load,
|
||||||
|
child: const Text('Retry'),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
TextButton(onPressed: controller.load, child: const Text('Retry')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
Widget _selectors(BuildContext context) {
|
||||||
|
if (usesCupertinoHost(context)) {
|
||||||
|
return Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
children: [
|
||||||
|
CupertinoButton(
|
||||||
|
onPressed: () => _choose(
|
||||||
|
context,
|
||||||
|
'Sort runs',
|
||||||
|
_sorts,
|
||||||
|
controller.sort,
|
||||||
|
controller.setSort,
|
||||||
|
),
|
||||||
|
child: Text('Sort: ${_sortLabel(controller.sort)}'),
|
||||||
|
),
|
||||||
|
CupertinoButton(
|
||||||
|
onPressed: () => _choose(
|
||||||
|
context,
|
||||||
|
'Schedule',
|
||||||
|
_schedules,
|
||||||
|
controller.scheduled,
|
||||||
|
controller.setScheduled,
|
||||||
|
),
|
||||||
|
child: Text('Schedule: ${_scheduleLabel(controller.scheduled)}'),
|
||||||
|
),
|
||||||
|
for (final status in _statuses)
|
||||||
|
CupertinoButton(
|
||||||
|
onPressed: () => controller.setStatus(status),
|
||||||
|
child: Text(
|
||||||
|
'${controller.statuses.contains(status) ? '✓ ' : ''}${_title(status)}',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
children: [
|
||||||
|
DropdownButton<String>(
|
||||||
|
value: controller.sort,
|
||||||
|
isExpanded: true,
|
||||||
|
onChanged: (v) {
|
||||||
|
if (v != null) controller.setSort(v);
|
||||||
|
},
|
||||||
|
items: _sorts
|
||||||
|
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
|
||||||
|
.toList(),
|
||||||
|
),
|
||||||
|
DropdownButton<String>(
|
||||||
|
value: controller.scheduled,
|
||||||
|
isExpanded: true,
|
||||||
|
onChanged: (v) {
|
||||||
|
if (v != null) controller.setScheduled(v);
|
||||||
|
},
|
||||||
|
items: _schedules
|
||||||
|
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
|
||||||
|
.toList(),
|
||||||
|
),
|
||||||
|
for (final status in _statuses)
|
||||||
|
FilterChip(
|
||||||
|
label: Text(_title(status)),
|
||||||
|
selected: controller.statuses.contains(status),
|
||||||
|
onSelected: (_) => controller.setStatus(status),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _choose(
|
||||||
|
BuildContext context,
|
||||||
|
String title,
|
||||||
|
List<(String, String)> values,
|
||||||
|
String selected,
|
||||||
|
ValueChanged<String> onSelected,
|
||||||
|
) async {
|
||||||
|
final value = await showCupertinoModalPopup<String>(
|
||||||
|
context: context,
|
||||||
|
builder: (context) => CupertinoActionSheet(
|
||||||
|
title: Text(title),
|
||||||
|
actions: [
|
||||||
|
for (final option in values)
|
||||||
|
CupertinoActionSheetAction(
|
||||||
|
onPressed: () => Navigator.pop(context, option.$1),
|
||||||
|
child: Text(option.$2),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
cancelButton: CupertinoActionSheetAction(
|
||||||
|
onPressed: () => Navigator.pop(context),
|
||||||
|
child: const Text('Cancel'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (value != null && value != selected) onSelected(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _runTile(BuildContext context, JsonMap run) {
|
||||||
|
final identity = runIdentity(run['title'], run['name']);
|
||||||
|
final id = run['id'];
|
||||||
|
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 (usesCupertinoHost(context)) {
|
||||||
|
return CupertinoListTile(
|
||||||
|
title: Text(title),
|
||||||
|
subtitle: Text(subtitle),
|
||||||
|
additionalInfo: Text(runStatusLabel(run)),
|
||||||
|
trailing: const CupertinoListTileChevron(),
|
||||||
|
onTap: id is num ? () => onSelected(id) : null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return ListTile(
|
||||||
|
title: Text(title),
|
||||||
|
subtitle: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [Text(subtitle), Text(runStatusLabel(run))],
|
||||||
|
),
|
||||||
|
trailing: const Icon(Icons.chevron_right),
|
||||||
|
onTap: id is num ? () => onSelected(id) : null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const _sorts = [
|
||||||
|
('newest_first', 'Newest'),
|
||||||
|
('oldest_first', 'Oldest'),
|
||||||
|
('pipeline_name', 'Pipeline'),
|
||||||
|
('status', 'Status'),
|
||||||
|
];
|
||||||
|
const _schedules = [
|
||||||
|
('any', 'Any schedule'),
|
||||||
|
('scheduled', 'Scheduled'),
|
||||||
|
('unscheduled', 'Unscheduled'),
|
||||||
|
];
|
||||||
|
const _statuses = ['queued', 'running', 'waiting', 'succeeded', 'failed'];
|
||||||
|
String _sortLabel(String value) =>
|
||||||
|
_sorts.firstWhere((e) => e.$1 == value, orElse: () => _sorts.first).$2;
|
||||||
|
String _scheduleLabel(String value) => _schedules
|
||||||
|
.firstWhere((e) => e.$1 == value, orElse: () => _schedules.first)
|
||||||
|
.$2;
|
||||||
|
String _title(String value) => '${value[0].toUpperCase()}${value.substring(1)}';
|
||||||
+3
-36
@@ -1,40 +1,7 @@
|
|||||||
import 'package:flutter/cupertino.dart';
|
import 'application/bootstrap.dart';
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
import 'shell/adaptive_shell.dart';
|
|
||||||
import 'shell/destination.dart';
|
|
||||||
|
|
||||||
|
export 'application/app.dart' show MyApp;
|
||||||
export 'shell/adaptive_shell.dart';
|
export 'shell/adaptive_shell.dart';
|
||||||
export 'shell/destination.dart';
|
export 'shell/destination.dart';
|
||||||
|
|
||||||
void main() => runApp(const MyApp());
|
void main() => runPipelinesApp();
|
||||||
|
|
||||||
class MyApp extends StatelessWidget {
|
|
||||||
const MyApp({super.key, this.destinationBodies = const {}, this.cupertino});
|
|
||||||
|
|
||||||
final Map<AppDestination, WidgetBuilder> 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),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -8,20 +8,46 @@ class AdaptiveShell extends StatefulWidget {
|
|||||||
super.key,
|
super.key,
|
||||||
this.destinationBodies = const {},
|
this.destinationBodies = const {},
|
||||||
this.cupertino = false,
|
this.cupertino = false,
|
||||||
|
this.destination,
|
||||||
|
this.onDestinationSelected,
|
||||||
});
|
});
|
||||||
|
|
||||||
final Map<AppDestination, WidgetBuilder> destinationBodies;
|
final Map<AppDestination, WidgetBuilder> destinationBodies;
|
||||||
final bool cupertino;
|
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<AppDestination>? onDestinationSelected;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<AdaptiveShell> createState() => _AdaptiveShellState();
|
State<AdaptiveShell> createState() => _AdaptiveShellState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _AdaptiveShellState extends State<AdaptiveShell> {
|
class _AdaptiveShellState extends State<AdaptiveShell> {
|
||||||
AppDestination _selected = AppDestination.pipelines;
|
late AppDestination _selected;
|
||||||
|
|
||||||
void _select(AppDestination destination) =>
|
@override
|
||||||
setState(() => _selected = destination);
|
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<T> _items<T>(T Function(AppDestination) build) =>
|
List<T> _items<T>(T Function(AppDestination) build) =>
|
||||||
AppDestination.values.map(build).toList();
|
AppDestination.values.map(build).toList();
|
||||||
|
|||||||
@@ -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<MaterialLocalizations>(context, MaterialLocalizations) ==
|
||||||
|
null;
|
||||||
+119
@@ -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.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# R1a — runs controller correctness
|
||||||
|
|
||||||
|
Implemented in `runs_controller.dart`: selection requests now retain prior detail while loading and ignore stale/disposed replies; list and detail loading indicators are independent; Back invalidates selection and cancels scheduled refresh; selected-run refreshes use captured ID/generation and preserve detail until the reply; identity-less or unresolvable run events trigger list resynchronization.
|
||||||
|
|
||||||
|
Added six fake-gateway regression tests in `test/features/runs/ui/runs_controller_test.dart` for stale selection, pending futures after disposal, Back cancellation, unrelated events, identity-less list resync, and full-refresh detail retention.
|
||||||
|
|
||||||
|
Verification: `flutter test test/features/runs/ui` passed (6 tests), `flutter analyze` passed with no issues, and `flutter build web` passed. Cupertino UI/browser evidence is outside this R1a slice and remains incomplete for the overall R1 task; mobile is unverified.
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# R1b — runs controller request independence
|
||||||
|
|
||||||
|
Focused correctness fix on retained candidate `6b8d5ea`. Files:
|
||||||
|
`lib/features/runs/ui/runs_controller.dart`,
|
||||||
|
`test/features/runs/ui/runs_controller_test.dart`.
|
||||||
|
|
||||||
|
## Fixes
|
||||||
|
|
||||||
|
- List and detail requests now use independent generations (`_listGeneration`,
|
||||||
|
`_detailGeneration`). `load(initialId)` no longer bumps the detail generation
|
||||||
|
that `select(initialId)` also advances, so both `loading` and `detailLoading`
|
||||||
|
clear when the requests resolve. Manual list loads also no longer invalidate
|
||||||
|
valid detail refreshes.
|
||||||
|
- List resyncs (`_reloadList`) capture and check a list generation, so a stale
|
||||||
|
reply cannot overwrite a newer `load()`. Concurrent resync requests are
|
||||||
|
coalesced into exactly one followup; a resync requested during a manual load
|
||||||
|
runs after that load instead of being dropped.
|
||||||
|
- Detail refreshes capture the current detail generation and selected run.
|
||||||
|
Same-id refreshes keep the existing detail and are coalesced (in-flight plus
|
||||||
|
one followup). Selecting a different run clears the previous detail instead of
|
||||||
|
presenting it as the new run. Back/dispose invalidate pending replies, and
|
||||||
|
stale requests cannot clear another generation's loading flags.
|
||||||
|
- Added `num? get selectedRunId` for the native UI lane. All existing public
|
||||||
|
methods and fields are preserved.
|
||||||
|
|
||||||
|
The existing 150 ms event debounce is retained; no polling or extra timers were
|
||||||
|
introduced. File is 260 lines; the fix stays within the controller responsibility
|
||||||
|
rather than fragmenting it.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
Extended `test/features/runs/ui/runs_controller_test.dart` with regressions for:
|
||||||
|
|
||||||
|
- `load(initialId)` resolves with `loading == false` and `detailLoading == false`.
|
||||||
|
- Overlapping list loads with reversed completion order: newer reply wins.
|
||||||
|
- List resync leaves the selected detail request valid.
|
||||||
|
- Manual `load()` does not invalidate an in-flight detail refresh.
|
||||||
|
- Sparse unknown run events coalesce into one followup resync.
|
||||||
|
- A followup requested while a superseded resync is still marked in flight
|
||||||
|
starts once that stale reply arrives instead of being stranded.
|
||||||
|
- Selected refresh coalescing (in-flight plus followup) and Back ignoring the
|
||||||
|
pending reply.
|
||||||
|
- Choosing another run does not display the previous run's detail.
|
||||||
|
- Pending detail refresh is safe after dispose.
|
||||||
|
|
||||||
|
Existing six regression tests remain and pass.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- `/Users/alan/development/flutter/bin/flutter test test/features/runs/ui` — 15 tests passed.
|
||||||
|
- `/Users/alan/development/flutter/bin/flutter test test/features/runs` — 26 tests passed.
|
||||||
|
- `/Users/alan/development/flutter/bin/flutter analyze` — no issues found.
|
||||||
|
- `flutter build web` not run in this NONVISUAL controller slice; manager
|
||||||
|
integration/UI review owns rendered and build acceptance.
|
||||||
|
- Mobile remains unverified; no device or browser tools used.
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# R1c2 — run detail native widget slice
|
||||||
|
|
||||||
|
## Change
|
||||||
|
|
||||||
|
`RunDetailView` keeps its existing `controller` and `onBack` API but now selects
|
||||||
|
its presentation from the host: MaterialApp uses the standard Material controls,
|
||||||
|
CupertinoApp uses Cupertino controls without a Material ancestor. Selection is
|
||||||
|
based on `MaterialLocalizations`, so it works on the web's desktop host and in
|
||||||
|
widget tests without relying on the browser's target platform.
|
||||||
|
|
||||||
|
- Material: `Chip`, `ExpansionTile`, `ListTile`, `TextButton`, `IconButton`,
|
||||||
|
selectable text and `SnackBar` feedback.
|
||||||
|
- Cupertino: `CupertinoButton`, `CupertinoExpansionTile`, `CupertinoListTile`
|
||||||
|
and grouped list sections. Copy feedback is inline in a live-region status;
|
||||||
|
no `ScaffoldMessenger`/`SnackBar` is used.
|
||||||
|
- Loading and failure states are platform-specific and honest: only the error
|
||||||
|
text is shown when no detail exists, and the Back action remains available.
|
||||||
|
A refresh with retained detail reports `Refreshing run details…` instead of
|
||||||
|
clearing the view.
|
||||||
|
- The scrollable list has a stable per-run key and a test proves a live detail
|
||||||
|
update keeps its scroll offset.
|
||||||
|
|
||||||
|
Detail-only helpers split formatting from presentation:
|
||||||
|
|
||||||
|
- `run_detail_content.dart`: title/pipeline, prompt extraction, nested JSON,
|
||||||
|
usage metrics and recorded timeline entries.
|
||||||
|
- `run_detail_material.dart` and `run_detail_cupertino.dart`: the two native
|
||||||
|
presentations.
|
||||||
|
- Input/output are pretty-printed, selectable JSON. Copy prompt passes the
|
||||||
|
stored string byte-for-byte (no trim, no fallback field).
|
||||||
|
- Usage distinguishes reported zero from unknown: token/cost totals are
|
||||||
|
`Unavailable` unless the corresponding stage count proves reporting; a known
|
||||||
|
stage count with an omitted zero cost renders `$0.000000`. Timeline rows show
|
||||||
|
the server's recorded sequence.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- `flutter test test/features/runs/ui/run_detail_widget_test.dart`: 7 tests
|
||||||
|
passed. They run both platforms at 390px width with 2x text, exercise
|
||||||
|
loading/error and Back, exact prompt copy and denied clipboard feedback,
|
||||||
|
nested JSON, recorded sequences, zero vs missing usage, and scroll retention.
|
||||||
|
- `flutter test test/features/runs`: 24 tests passed.
|
||||||
|
- `flutter analyze`: no issues.
|
||||||
|
- `flutter build web`: succeeded.
|
||||||
|
|
||||||
|
## Limits
|
||||||
|
|
||||||
|
No real browser interaction or rendered capture was performed in this slice; the
|
||||||
|
manager separately tracks R1 browser acceptance. Android/iOS builds and devices
|
||||||
|
were not run, so mobile is unverified. No commit, push or deployment was made.
|
||||||
+1
-1
@@ -108,7 +108,7 @@ packages:
|
|||||||
source: sdk
|
source: sdk
|
||||||
version: "0.0.0"
|
version: "0.0.0"
|
||||||
flutter_web_plugins:
|
flutter_web_plugins:
|
||||||
dependency: transitive
|
dependency: "direct main"
|
||||||
description: flutter
|
description: flutter
|
||||||
source: sdk
|
source: sdk
|
||||||
version: "0.0.0"
|
version: "0.0.0"
|
||||||
|
|||||||
@@ -36,6 +36,8 @@ dependencies:
|
|||||||
cupertino_icons: ^1.0.8
|
cupertino_icons: ^1.0.8
|
||||||
web_socket_channel: ^3.0.3
|
web_socket_channel: ^3.0.3
|
||||||
shared_preferences: ^2.5.6
|
shared_preferences: ^2.5.6
|
||||||
|
flutter_web_plugins:
|
||||||
|
sdk: flutter
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
|||||||
@@ -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');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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<void> flush() => Future<void>.delayed(Duration.zero);
|
||||||
|
|
||||||
|
Future<void> waitFor(bool Function() condition, String reason) async {
|
||||||
|
for (var attempt = 0; attempt < 200; attempt++) {
|
||||||
|
if (condition()) return;
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||||||
|
}
|
||||||
|
fail('Timed out: $reason');
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> types(FakeChannel channel) => [
|
||||||
|
for (final frame in channel.outgoing)
|
||||||
|
(jsonDecode(frame as String) as Map<String, dynamic>)['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<String, dynamic>;
|
||||||
|
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<String, dynamic>;
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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<String, dynamic>? requestOf(FakeChannel channel, String type) => channel
|
||||||
|
.outgoing
|
||||||
|
.map((frame) => jsonDecode(frame as String) as Map<String, dynamic>)
|
||||||
|
.where((frame) => frame['type'] == type)
|
||||||
|
.firstOrNull;
|
||||||
|
|
||||||
|
Future<void> 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<void> replyList(
|
||||||
|
WidgetTester tester,
|
||||||
|
FakeChannel channel, {
|
||||||
|
required List<Map<String, dynamic>> 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<void> 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);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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<int>? onRunSelected,
|
||||||
|
VoidCallback? onBack,
|
||||||
|
}) => MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: RunsDestination(
|
||||||
|
session: session,
|
||||||
|
server: server,
|
||||||
|
initialRunId: initialRunId,
|
||||||
|
onRunSelected: onRunSelected,
|
||||||
|
onBack: onBack,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic>? listRequest(FakeChannel channel) => channel.outgoing
|
||||||
|
.map((frame) => jsonDecode(frame as String) as Map<String, dynamic>)
|
||||||
|
.where((frame) => frame['type'] == 'list_runs')
|
||||||
|
.firstOrNull;
|
||||||
|
|
||||||
|
Iterable<Map<String, dynamic>> detailRequests(FakeChannel channel, int id) =>
|
||||||
|
channel.outgoing
|
||||||
|
.map((frame) => jsonDecode(frame as String) as Map<String, dynamic>)
|
||||||
|
.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);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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'));
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/cupertino.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/core/api_gateway.dart';
|
||||||
|
import 'package:pipelines_app/features/runs/data/runs_repository.dart';
|
||||||
|
import 'package:pipelines_app/features/runs/ui/run_detail_view.dart';
|
||||||
|
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
|
||||||
|
|
||||||
|
enum AppPlatform { material, cupertino }
|
||||||
|
|
||||||
|
class FakeGateway implements ApiGateway {
|
||||||
|
FakeGateway(this.detail);
|
||||||
|
JsonMap detail;
|
||||||
|
Object? failure;
|
||||||
|
Completer<JsonMap>? hold;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<JsonMap> get frames => const Stream<JsonMap>.empty();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
|
||||||
|
if (type != 'get_run') throw UnsupportedError(type);
|
||||||
|
if (hold != null) return hold!.future;
|
||||||
|
if (failure != null) return Future.error(failure!);
|
||||||
|
return Future.value({'run_detail': detail});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const prompt = ' keep\n\nspacing ';
|
||||||
|
|
||||||
|
JsonMap runFixture({JsonMap? usage, int steps = 2}) {
|
||||||
|
final run = <String, dynamic>{
|
||||||
|
'id': 7,
|
||||||
|
'title': 'Nightly build',
|
||||||
|
'name': 'release',
|
||||||
|
'status': 'succeeded',
|
||||||
|
'input': {
|
||||||
|
'prompt': prompt,
|
||||||
|
'nested': {
|
||||||
|
'alpha': 1,
|
||||||
|
'items': [1, 2],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'output': {
|
||||||
|
'result': {'ok': true},
|
||||||
|
},
|
||||||
|
'steps': [
|
||||||
|
for (var i = 0; i < steps; i++)
|
||||||
|
{
|
||||||
|
'stage': i == 0 ? 'build' : 'test',
|
||||||
|
'sequence': i + 3,
|
||||||
|
'status': 'completed',
|
||||||
|
'outcome': 'success',
|
||||||
|
'target': '#success',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
if (usage != null) run['usage'] = usage;
|
||||||
|
return run;
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonMap usageFixture({int known = 1}) => {
|
||||||
|
'stages': 1,
|
||||||
|
'tokens_total': 0,
|
||||||
|
'tokens_known_stages': known,
|
||||||
|
'tokens_in': 0,
|
||||||
|
'tokens_out': 0,
|
||||||
|
'split_known': true,
|
||||||
|
'cost_known_stages': known,
|
||||||
|
};
|
||||||
|
|
||||||
|
Future<void> pumpDetail(
|
||||||
|
WidgetTester tester,
|
||||||
|
AppPlatform platform,
|
||||||
|
RunsController controller, {
|
||||||
|
VoidCallback? onBack,
|
||||||
|
bool settle = true,
|
||||||
|
}) async {
|
||||||
|
tester.view.physicalSize = const Size(390, 1600);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
final view = RunDetailView(controller: controller, onBack: onBack ?? () {});
|
||||||
|
final page = MediaQuery(
|
||||||
|
data: MediaQueryData.fromView(
|
||||||
|
tester.view,
|
||||||
|
).copyWith(textScaler: const TextScaler.linear(2)),
|
||||||
|
child: view,
|
||||||
|
);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
platform == AppPlatform.material
|
||||||
|
? MaterialApp(home: Scaffold(body: page))
|
||||||
|
: CupertinoApp(
|
||||||
|
home: CupertinoPageScaffold(child: SafeArea(child: page)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (settle) {
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
} else {
|
||||||
|
await tester.pump();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void mockClipboard(
|
||||||
|
WidgetTester tester,
|
||||||
|
List<String> copied, {
|
||||||
|
bool Function()? denied,
|
||||||
|
}) {
|
||||||
|
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||||
|
SystemChannels.platform,
|
||||||
|
(call) async {
|
||||||
|
if (call.method != 'Clipboard.setData') return null;
|
||||||
|
if (denied?.call() ?? false) {
|
||||||
|
throw PlatformException(code: 'clipboard-denied');
|
||||||
|
}
|
||||||
|
copied.add((call.arguments as Map)['text'] as String);
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
addTearDown(
|
||||||
|
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||||
|
SystemChannels.platform,
|
||||||
|
null,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
late FakeGateway gateway;
|
||||||
|
late RunsController controller;
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
gateway = FakeGateway(runFixture());
|
||||||
|
controller = RunsController(RunsRepository(gateway));
|
||||||
|
});
|
||||||
|
tearDown(() => controller.dispose());
|
||||||
|
|
||||||
|
for (final platform in AppPlatform.values) {
|
||||||
|
testWidgets('${platform.name} detail at 390 with 2x text', (tester) async {
|
||||||
|
gateway.detail = runFixture(steps: 12);
|
||||||
|
await controller.select(1);
|
||||||
|
await pumpDetail(tester, platform, controller);
|
||||||
|
expect(tester.takeException(), isNull);
|
||||||
|
expect(find.text('Nightly build'), findsOneWidget);
|
||||||
|
expect(find.textContaining('Original prompt'), findsOneWidget);
|
||||||
|
if (platform == AppPlatform.material) {
|
||||||
|
expect(find.byType(Chip), findsOneWidget);
|
||||||
|
expect(find.byType(ExpansionTile), findsNWidgets(2));
|
||||||
|
} else {
|
||||||
|
expect(find.byType(Material), findsNothing);
|
||||||
|
expect(find.byType(Chip), findsNothing);
|
||||||
|
expect(find.byType(CupertinoExpansionTile), findsNWidgets(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
await tester.tap(find.text('Input'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.textContaining('"alpha": 1'), findsOneWidget);
|
||||||
|
await tester.scrollUntilVisible(
|
||||||
|
find.text('Output'),
|
||||||
|
200,
|
||||||
|
scrollable: find.byType(Scrollable).first,
|
||||||
|
);
|
||||||
|
await tester.tap(find.text('Output'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.textContaining('"ok": true'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.scrollUntilVisible(
|
||||||
|
find.textContaining('build · visit 3'),
|
||||||
|
200,
|
||||||
|
scrollable: find.byType(Scrollable).first,
|
||||||
|
);
|
||||||
|
expect(find.textContaining('build · visit 3'), findsOneWidget);
|
||||||
|
expect(find.textContaining('test · visit 4'), findsOneWidget);
|
||||||
|
if (platform == AppPlatform.material) {
|
||||||
|
final scrollable = tester.state<ScrollableState>(
|
||||||
|
find.byType(Scrollable).first,
|
||||||
|
);
|
||||||
|
final before = scrollable.position.pixels;
|
||||||
|
expect(before, greaterThan(0));
|
||||||
|
gateway.detail = runFixture(steps: 13);
|
||||||
|
await controller.select(1);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(scrollable.position.pixels, closeTo(before, 0.1));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('${platform.name} loading and error stay honest', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
gateway.hold = Completer<JsonMap>();
|
||||||
|
final pending = controller.select(1);
|
||||||
|
await pumpDetail(tester, platform, controller, settle: false);
|
||||||
|
expect(find.text('Loading run details…'), findsOneWidget);
|
||||||
|
expect(
|
||||||
|
find.byType(
|
||||||
|
platform == AppPlatform.material
|
||||||
|
? CircularProgressIndicator
|
||||||
|
: CupertinoActivityIndicator,
|
||||||
|
),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
gateway.hold!.complete({'run_detail': runFixture()});
|
||||||
|
await pending;
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Nightly build'), findsOneWidget);
|
||||||
|
|
||||||
|
controller.dispose();
|
||||||
|
gateway = FakeGateway(runFixture())
|
||||||
|
..failure = StateError('server unavailable');
|
||||||
|
controller = RunsController(RunsRepository(gateway));
|
||||||
|
await controller.select(1);
|
||||||
|
var backs = 0;
|
||||||
|
await pumpDetail(tester, platform, controller, onBack: () => backs++);
|
||||||
|
expect(find.textContaining('server unavailable'), findsOneWidget);
|
||||||
|
await tester.tap(find.text('Back to list'));
|
||||||
|
expect(backs, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('${platform.name} copies the exact prompt and reports denial', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final copied = <String>[];
|
||||||
|
var denied = false;
|
||||||
|
mockClipboard(tester, copied, denied: () => denied);
|
||||||
|
final copy = platform == AppPlatform.material
|
||||||
|
? find.byTooltip('Copy prompt')
|
||||||
|
: find.text('Copy prompt');
|
||||||
|
await controller.select(1);
|
||||||
|
await pumpDetail(tester, platform, controller);
|
||||||
|
await tester.tap(copy);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(copied.single, prompt);
|
||||||
|
expect(find.text('Prompt copied to clipboard.'), findsOneWidget);
|
||||||
|
if (platform == AppPlatform.material) {
|
||||||
|
await tester.pump(const Duration(seconds: 5));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
}
|
||||||
|
denied = true;
|
||||||
|
await tester.tap(copy);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Could not copy prompt to clipboard.'), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('reported zero and missing usage stay distinct', (tester) async {
|
||||||
|
gateway.detail = runFixture(usage: usageFixture());
|
||||||
|
await controller.select(1);
|
||||||
|
await pumpDetail(tester, AppPlatform.material, controller);
|
||||||
|
await tester.tap(find.text('Metrics'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Unavailable'), findsNothing);
|
||||||
|
expect(find.text('0'), findsNWidgets(3));
|
||||||
|
expect(find.text('\$0.000000'), findsOneWidget);
|
||||||
|
|
||||||
|
gateway.detail = runFixture(usage: usageFixture(known: 0));
|
||||||
|
await controller.select(1);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Unavailable'), findsNWidgets(4));
|
||||||
|
expect(find.text('0'), findsNothing);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,344 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/core/api_gateway.dart';
|
||||||
|
import 'package:pipelines_app/features/runs/data/runs_repository.dart';
|
||||||
|
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
|
||||||
|
|
||||||
|
class FakeGateway implements ApiGateway {
|
||||||
|
final framesController = StreamController<JsonMap>.broadcast();
|
||||||
|
final lists = <Completer<JsonMap>>[];
|
||||||
|
final details = <num, List<Completer<JsonMap>>>{};
|
||||||
|
int listCalls = 0;
|
||||||
|
@override
|
||||||
|
Stream<JsonMap> get frames => framesController.stream;
|
||||||
|
@override
|
||||||
|
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
|
||||||
|
if (type == 'list_runs') {
|
||||||
|
listCalls++;
|
||||||
|
final request = Completer<JsonMap>();
|
||||||
|
lists.add(request);
|
||||||
|
return request.future;
|
||||||
|
}
|
||||||
|
final id = fields['run_id'] as num;
|
||||||
|
final request = Completer<JsonMap>();
|
||||||
|
details.putIfAbsent(id, () => []).add(request);
|
||||||
|
return request.future;
|
||||||
|
}
|
||||||
|
|
||||||
|
void listReply(int index, List<JsonMap> runs) =>
|
||||||
|
lists[index].complete({'runs': runs});
|
||||||
|
void detailReply(num id, int index, JsonMap value) =>
|
||||||
|
details[id]![index].complete({'run_detail': value});
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
late FakeGateway gateway;
|
||||||
|
late RunsController controller;
|
||||||
|
var disposed = false;
|
||||||
|
setUp(() {
|
||||||
|
gateway = FakeGateway();
|
||||||
|
controller = RunsController(RunsRepository(gateway));
|
||||||
|
disposed = false;
|
||||||
|
});
|
||||||
|
tearDown(() {
|
||||||
|
if (!disposed) controller.dispose();
|
||||||
|
gateway.framesController.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('late selection response cannot replace latest selection', () async {
|
||||||
|
final first = controller.select(1);
|
||||||
|
final second = controller.select(2);
|
||||||
|
gateway.detailReply(2, 0, {'id': 2});
|
||||||
|
await second;
|
||||||
|
gateway.detailReply(1, 0, {'id': 1});
|
||||||
|
await first;
|
||||||
|
expect(controller.detail?['id'], 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pending load and selection futures are safe after dispose', () async {
|
||||||
|
final load = controller.load();
|
||||||
|
final select = controller.select(1);
|
||||||
|
controller.dispose();
|
||||||
|
disposed = true;
|
||||||
|
gateway.listReply(0, []);
|
||||||
|
gateway.detailReply(1, 0, {'id': 1});
|
||||||
|
await Future.wait([load, select]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Back cancels scheduled detail refresh', () async {
|
||||||
|
final select = controller.select(1);
|
||||||
|
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
|
||||||
|
await select;
|
||||||
|
controller.listen(gateway.frames);
|
||||||
|
gateway.framesController.add({
|
||||||
|
'type': 'run_event',
|
||||||
|
'run_id': 1,
|
||||||
|
'status': 'succeeded',
|
||||||
|
});
|
||||||
|
controller.back();
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 220));
|
||||||
|
expect(gateway.details[1], hasLength(1));
|
||||||
|
expect(controller.detail, isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unrelated run event does not refresh selected detail', () async {
|
||||||
|
final select = controller.select(1);
|
||||||
|
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
|
||||||
|
await select;
|
||||||
|
controller.listen(gateway.frames);
|
||||||
|
gateway.framesController.add({
|
||||||
|
'type': 'run_event',
|
||||||
|
'run_id': 2,
|
||||||
|
'status': 'succeeded',
|
||||||
|
});
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 220));
|
||||||
|
expect(gateway.details[1], hasLength(1));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('identity-less event reloads list', () async {
|
||||||
|
controller.listen(gateway.frames);
|
||||||
|
gateway.framesController.add({'type': 'run_event', 'status': 'running'});
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(gateway.listCalls, 1);
|
||||||
|
gateway.listReply(0, [
|
||||||
|
{'id': 3},
|
||||||
|
]);
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(controller.runs.single['id'], 3);
|
||||||
|
expect(controller.loading, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'full refresh is coalesced and keeps current detail until reply',
|
||||||
|
() async {
|
||||||
|
final select = controller.select(1);
|
||||||
|
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
|
||||||
|
await select;
|
||||||
|
controller.listen(gateway.frames);
|
||||||
|
gateway.framesController.add({
|
||||||
|
'type': 'run_event',
|
||||||
|
'run_id': 1,
|
||||||
|
'status': 'succeeded',
|
||||||
|
});
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 180));
|
||||||
|
expect(controller.detail?['id'], 1);
|
||||||
|
expect(gateway.details[1], hasLength(2));
|
||||||
|
gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'});
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(controller.detail?['status'], 'succeeded');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('load with initial id clears list and detail loading', () async {
|
||||||
|
final load = controller.load(7);
|
||||||
|
expect(controller.loading, isTrue);
|
||||||
|
gateway.listReply(0, [
|
||||||
|
{'id': 7},
|
||||||
|
{'id': 8},
|
||||||
|
]);
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(gateway.details[7], hasLength(1));
|
||||||
|
expect(controller.loading, isFalse);
|
||||||
|
expect(controller.detailLoading, isTrue);
|
||||||
|
gateway.detailReply(7, 0, {'id': 7});
|
||||||
|
await load;
|
||||||
|
expect(controller.loading, isFalse);
|
||||||
|
expect(controller.detailLoading, isFalse);
|
||||||
|
expect(controller.detail?['id'], 7);
|
||||||
|
expect(controller.selectedRunId, 7);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('newer list load wins when replies complete out of order', () async {
|
||||||
|
final first = controller.load();
|
||||||
|
final second = controller.load();
|
||||||
|
gateway.listReply(1, [
|
||||||
|
{'id': 2},
|
||||||
|
]);
|
||||||
|
await second;
|
||||||
|
gateway.listReply(0, [
|
||||||
|
{'id': 1},
|
||||||
|
]);
|
||||||
|
await first;
|
||||||
|
expect(controller.runs.single['id'], 2);
|
||||||
|
expect(controller.loading, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('list resync leaves the selected detail request valid', () async {
|
||||||
|
final select = controller.select(1);
|
||||||
|
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
|
||||||
|
await select;
|
||||||
|
controller.listen(gateway.frames);
|
||||||
|
gateway.framesController.add({'type': 'run_event', 'status': 'running'});
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(gateway.listCalls, 1);
|
||||||
|
gateway.listReply(0, [
|
||||||
|
{'id': 1, 'status': 'running'},
|
||||||
|
]);
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(controller.detail?['id'], 1);
|
||||||
|
expect(controller.selectedRunId, 1);
|
||||||
|
expect(gateway.details[1], hasLength(1));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('manual list load keeps an in-flight detail refresh valid', () async {
|
||||||
|
final select = controller.select(1);
|
||||||
|
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
|
||||||
|
await select;
|
||||||
|
controller.listen(gateway.frames);
|
||||||
|
gateway.framesController.add({
|
||||||
|
'type': 'run_event',
|
||||||
|
'run_id': 1,
|
||||||
|
'status': 'succeeded',
|
||||||
|
});
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 180));
|
||||||
|
expect(gateway.details[1], hasLength(2));
|
||||||
|
final load = controller.load();
|
||||||
|
gateway.listReply(1, [
|
||||||
|
{'id': 1},
|
||||||
|
]);
|
||||||
|
await load;
|
||||||
|
gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'});
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(controller.detail?['status'], 'succeeded');
|
||||||
|
expect(controller.detailLoading, isFalse);
|
||||||
|
gateway.listReply(0, [
|
||||||
|
{'id': 1},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('event during a superseded resync still runs one followup', () async {
|
||||||
|
controller.listen(gateway.frames);
|
||||||
|
gateway.framesController.add({
|
||||||
|
'type': 'run_event',
|
||||||
|
'run_id': 9,
|
||||||
|
'status': 'running',
|
||||||
|
});
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(gateway.listCalls, 1);
|
||||||
|
final load = controller.load();
|
||||||
|
expect(gateway.listCalls, 2);
|
||||||
|
gateway.listReply(1, [
|
||||||
|
{'id': 1},
|
||||||
|
]);
|
||||||
|
await load;
|
||||||
|
gateway.framesController.add({
|
||||||
|
'type': 'run_event',
|
||||||
|
'run_id': 10,
|
||||||
|
'status': 'running',
|
||||||
|
});
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(gateway.listCalls, 2);
|
||||||
|
gateway.listReply(0, [
|
||||||
|
{'id': 1},
|
||||||
|
]);
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(gateway.listCalls, 3);
|
||||||
|
gateway.listReply(2, [
|
||||||
|
{'id': 1},
|
||||||
|
{'id': 2},
|
||||||
|
]);
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(controller.runs, hasLength(2));
|
||||||
|
expect(controller.loading, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unknown run events coalesce into one followup resync', () async {
|
||||||
|
controller.listen(gateway.frames);
|
||||||
|
gateway.framesController.add({
|
||||||
|
'type': 'run_event',
|
||||||
|
'run_id': 9,
|
||||||
|
'status': 'running',
|
||||||
|
});
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(gateway.listCalls, 1);
|
||||||
|
expect(controller.loading, isTrue);
|
||||||
|
gateway.framesController.add({
|
||||||
|
'type': 'run_event',
|
||||||
|
'run_id': 10,
|
||||||
|
'status': 'running',
|
||||||
|
});
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(gateway.listCalls, 1);
|
||||||
|
gateway.listReply(0, [
|
||||||
|
{'id': 3},
|
||||||
|
]);
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(gateway.listCalls, 2);
|
||||||
|
expect(controller.loading, isTrue);
|
||||||
|
gateway.listReply(1, [
|
||||||
|
{'id': 3},
|
||||||
|
{'id': 4},
|
||||||
|
]);
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(gateway.listCalls, 2);
|
||||||
|
expect(controller.loading, isFalse);
|
||||||
|
expect(controller.runs, hasLength(2));
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'selected refresh coalesces and Back ignores the pending reply',
|
||||||
|
() async {
|
||||||
|
final select = controller.select(1);
|
||||||
|
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
|
||||||
|
await select;
|
||||||
|
controller.listen(gateway.frames);
|
||||||
|
gateway.framesController.add({
|
||||||
|
'type': 'run_event',
|
||||||
|
'run_id': 1,
|
||||||
|
'status': 'succeeded',
|
||||||
|
});
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 180));
|
||||||
|
expect(gateway.details[1], hasLength(2));
|
||||||
|
gateway.framesController.add({
|
||||||
|
'type': 'run_event',
|
||||||
|
'run_id': 1,
|
||||||
|
'status': 'failed',
|
||||||
|
});
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(gateway.details[1], hasLength(2));
|
||||||
|
gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'});
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(gateway.details[1], hasLength(3));
|
||||||
|
controller.back();
|
||||||
|
gateway.detailReply(1, 2, {'id': 1, 'status': 'failed'});
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(controller.detail, isNull);
|
||||||
|
expect(controller.detailLoading, isFalse);
|
||||||
|
expect(controller.error, isNull);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('choosing another run does not display the previous detail', () async {
|
||||||
|
final first = controller.select(1);
|
||||||
|
gateway.detailReply(1, 0, {'id': 1});
|
||||||
|
await first;
|
||||||
|
final second = controller.select(2);
|
||||||
|
expect(controller.detail, isNull);
|
||||||
|
expect(controller.selectedRunId, 2);
|
||||||
|
expect(controller.detailLoading, isTrue);
|
||||||
|
gateway.detailReply(2, 0, {'id': 2});
|
||||||
|
await second;
|
||||||
|
expect(controller.detail?['id'], 2);
|
||||||
|
expect(controller.detailLoading, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pending detail refresh is safe after dispose', () async {
|
||||||
|
final select = controller.select(1);
|
||||||
|
gateway.detailReply(1, 0, {'id': 1, 'status': 'running'});
|
||||||
|
await select;
|
||||||
|
controller.listen(gateway.frames);
|
||||||
|
gateway.framesController.add({
|
||||||
|
'type': 'run_event',
|
||||||
|
'run_id': 1,
|
||||||
|
'status': 'succeeded',
|
||||||
|
});
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 180));
|
||||||
|
expect(gateway.details[1], hasLength(2));
|
||||||
|
controller.dispose();
|
||||||
|
disposed = true;
|
||||||
|
gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'});
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
expect(controller.detail?['id'], 1);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
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/data/runs_repository.dart';
|
||||||
|
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
|
||||||
|
import 'package:pipelines_app/features/runs/ui/runs_list.dart';
|
||||||
|
|
||||||
|
class _Gateway implements ApiGateway {
|
||||||
|
final framesController = StreamController<JsonMap>.broadcast();
|
||||||
|
JsonMap? reply;
|
||||||
|
Object? failure;
|
||||||
|
Completer<void>? gate;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<JsonMap> get frames => framesController.stream;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||||
|
await gate?.future;
|
||||||
|
if (failure != null) throw failure!;
|
||||||
|
return reply ?? {'runs': []};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
late _Gateway gateway;
|
||||||
|
late RunsController controller;
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
gateway = _Gateway();
|
||||||
|
controller = RunsController(RunsRepository(gateway));
|
||||||
|
});
|
||||||
|
|
||||||
|
tearDown(() async {
|
||||||
|
controller.dispose();
|
||||||
|
await gateway.framesController.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
Future<void> mount(
|
||||||
|
WidgetTester tester, {
|
||||||
|
required bool cupertino,
|
||||||
|
ValueChanged<num>? onSelected,
|
||||||
|
}) async {
|
||||||
|
gateway.reply = {
|
||||||
|
'runs': [
|
||||||
|
{'id': 1, 'name': 'Alpha', 'status': 'running', 'scheduled': true},
|
||||||
|
{'id': 2, 'name': 'Beta', 'status': 'failed', 'scheduled': false},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
await controller.load();
|
||||||
|
final list = AnimatedBuilder(
|
||||||
|
animation: controller,
|
||||||
|
builder: (context, _) =>
|
||||||
|
RunsList(controller: controller, onSelected: onSelected ?? (_) {}),
|
||||||
|
);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
cupertino
|
||||||
|
? CupertinoApp(home: CupertinoPageScaffold(child: list))
|
||||||
|
: MaterialApp(home: Scaffold(body: list)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'uses native search and filters runs in CupertinoApp',
|
||||||
|
(tester) async {
|
||||||
|
num? selectedRun;
|
||||||
|
await mount(
|
||||||
|
tester,
|
||||||
|
cupertino: true,
|
||||||
|
onSelected: (id) => selectedRun = id,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(find.byType(CupertinoSearchTextField), findsOneWidget);
|
||||||
|
expect(find.text('Alpha'), findsOneWidget);
|
||||||
|
await tester.enterText(find.byType(CupertinoSearchTextField), 'Beta');
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Beta'), findsNWidgets(2));
|
||||||
|
expect(find.text('Alpha'), findsNothing);
|
||||||
|
await tester.tap(find.byType(CupertinoListTile));
|
||||||
|
expect(selectedRun, 2);
|
||||||
|
await tester.enterText(find.byType(CupertinoSearchTextField), 'missing');
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('No runs found.'), findsOneWidget);
|
||||||
|
await tester.enterText(find.byType(CupertinoSearchTextField), '');
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.textContaining('Schedule:'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Scheduled'), findsWidgets);
|
||||||
|
await tester.tap(find.text('Scheduled').last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(controller.scheduled, 'scheduled');
|
||||||
|
},
|
||||||
|
variant: TargetPlatformVariant.only(TargetPlatform.iOS),
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'retains Material controls and handles large text on narrow layout',
|
||||||
|
(tester) async {
|
||||||
|
tester.view.devicePixelRatio = 2;
|
||||||
|
tester.view.physicalSize = const Size(780, 1560);
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
builder: (context, child) => MediaQuery(
|
||||||
|
data: MediaQuery.of(
|
||||||
|
context,
|
||||||
|
).copyWith(textScaler: const TextScaler.linear(2)),
|
||||||
|
child: child!,
|
||||||
|
),
|
||||||
|
home: Scaffold(
|
||||||
|
body: AnimatedBuilder(
|
||||||
|
animation: controller,
|
||||||
|
builder: (_, _) =>
|
||||||
|
RunsList(controller: controller, onSelected: (_) {}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
gateway.reply = {
|
||||||
|
'runs': [
|
||||||
|
{'id': 1, 'name': 'Alpha', 'status': 'running', 'scheduled': true},
|
||||||
|
{'id': 2, 'name': 'Beta', 'status': 'failed', 'scheduled': false},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
await controller.load();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byType(TextField), findsOneWidget);
|
||||||
|
final layoutError = tester.takeException();
|
||||||
|
expect(
|
||||||
|
layoutError,
|
||||||
|
isNull,
|
||||||
|
reason: layoutError is FlutterError
|
||||||
|
? layoutError.toStringDeep()
|
||||||
|
: '$layoutError',
|
||||||
|
);
|
||||||
|
},
|
||||||
|
variant: TargetPlatformVariant.only(TargetPlatform.android),
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'shows loading, error and server-empty states distinctly',
|
||||||
|
(tester) async {
|
||||||
|
gateway.failure = StateError('offline');
|
||||||
|
gateway.gate = Completer<void>();
|
||||||
|
final loading = controller.load();
|
||||||
|
await tester.pumpWidget(
|
||||||
|
CupertinoApp(
|
||||||
|
home: CupertinoPageScaffold(
|
||||||
|
child: AnimatedBuilder(
|
||||||
|
animation: controller,
|
||||||
|
builder: (_, child) =>
|
||||||
|
RunsList(controller: controller, onSelected: (_) {}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.byType(CupertinoActivityIndicator), findsOneWidget);
|
||||||
|
gateway.gate!.complete();
|
||||||
|
await loading;
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.textContaining('offline'), findsOneWidget);
|
||||||
|
expect(tester.takeException(), isNull);
|
||||||
|
gateway.failure = null;
|
||||||
|
gateway.gate = null;
|
||||||
|
gateway.reply = {'runs': []};
|
||||||
|
await controller.load();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('No runs found.'), findsOneWidget);
|
||||||
|
expect(find.textContaining('offline'), findsNothing);
|
||||||
|
expect(tester.takeException(), isNull);
|
||||||
|
},
|
||||||
|
variant: TargetPlatformVariant.only(TargetPlatform.iOS),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<JsonMap>.broadcast();
|
||||||
|
final listRequests = <Completer<JsonMap>>[];
|
||||||
|
final detailRequests = <num, List<Completer<JsonMap>>>{};
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<JsonMap> get frames => framesController.stream;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
|
||||||
|
final request = Completer<JsonMap>();
|
||||||
|
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<JsonMap> 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<int>? onRunSelected,
|
||||||
|
VoidCallback? onBack,
|
||||||
|
}) => MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: RunsScreen(
|
||||||
|
gateway: gateway,
|
||||||
|
initialRunId: initialRunId,
|
||||||
|
syncToken: syncToken,
|
||||||
|
onRunSelected: onRunSelected,
|
||||||
|
onBack: onBack,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
Future<void> _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),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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=<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}`);
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
@@ -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();
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user