feat(app): compose live Runs with deep links and reconnect retention

This commit is contained in:
2026-10-21 17:26:36 +01:00
parent 38b7a849a7
commit 35a8aab772
34 changed files with 3038 additions and 128 deletions
+79
View File
@@ -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;
}
+96
View File
@@ -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);
}
+106
View File
@@ -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));
}
+168
View File
@@ -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();
}
}
+10
View File
@@ -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();
+20
View File
@@ -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));
}
+129
View File
@@ -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;
}
+249
View File
@@ -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')),
],
),
),
);
}
}
+65
View File
@@ -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);
}
}
}
+12 -10
View File
@@ -10,6 +10,11 @@ const runStates = [
'interrupted',
];
/// The largest millisecond value [DateTime] supports, and also exactly
/// representable by the web's JavaScript numbers. The previous
/// `0x7fffffffffffffff` literals failed dart2js compilation.
const int _maxMillis = 8640000000000000;
({String label, String? pipeline}) runIdentity(dynamic title, dynamic name) {
final stored = '${title ?? ''}'.trim();
return (
@@ -116,25 +121,22 @@ List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
int primary;
switch (sort) {
case 'oldest_first':
primary = cmp(at ?? 0x7fffffffffffffff, bt ?? 0x7fffffffffffffff);
primary = cmp(at ?? _maxMillis, bt ?? _maxMillis);
break;
case 'longest_duration':
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
if (primary == 0) primary = cmp(duration(b) ?? -1, duration(a) ?? -1);
if (primary == 0) {
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
case 'shortest_duration':
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
if (primary == 0) {
primary = cmp(
duration(a) ?? 0x7fffffffffffffff,
duration(b) ?? 0x7fffffffffffffff,
);
primary = cmp(duration(a) ?? _maxMillis, duration(b) ?? _maxMillis);
}
if (primary == 0) {
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
case 'pipeline_name':
@@ -142,7 +144,7 @@ List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
'${b['name'] ?? ''}'.toLowerCase(),
);
if (primary == 0) {
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
case 'status':
@@ -150,11 +152,11 @@ List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
'${b['status'] ?? ''}'.toLowerCase(),
);
if (primary == 0) {
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
default:
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
return primary == 0
? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0)
+73 -40
View File
@@ -1,80 +1,113 @@
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import '../../core/api_gateway.dart';
import 'data/runs_repository.dart';
import 'ui/run_detail_view.dart';
import 'ui/runs_controller.dart';
import 'ui/runs_list.dart';
import 'ui/run_detail_view.dart';
/// The runs destination's list/detail switch.
///
/// The controller's `selectedRunId` is the only selection source, so an
/// initial run, a pending detail, a failed detail, Back and a route change all
/// navigate the same way. The shell owns the app bar; this screen adds no
/// second one.
class RunsScreen extends StatefulWidget {
const RunsScreen({super.key, required this.gateway, this.initialRunId});
const RunsScreen({
super.key,
required this.gateway,
this.initialRunId,
this.syncToken = 0,
this.onRunSelected,
this.onBack,
});
final ApiGateway gateway;
/// The run the current route names, or null for the list.
final int? initialRunId;
/// Advances when the shared socket is replaced. The loaded screen refreshes
/// in place instead of being remounted, so its selection survives.
final int syncToken;
final ValueChanged<int>? onRunSelected;
final VoidCallback? onBack;
@override
State<RunsScreen> createState() => _RunsScreenState();
}
class _RunsScreenState extends State<RunsScreen> {
late RunsController controller;
num? _selectedRunId;
late final RunsController controller;
num? _shownRunId;
@override
void initState() {
super.initState();
controller = RunsController(RunsRepository(widget.gateway));
controller.listen(widget.gateway.frames);
controller.addListener(_changed);
controller.addListener(_selectionChanged);
controller.load(widget.initialRunId);
}
void _changed() {
@override
void didUpdateWidget(covariant RunsScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.syncToken != oldWidget.syncToken) {
controller.resync();
}
if (widget.initialRunId != oldWidget.initialRunId) {
final id = widget.initialRunId;
if (id == null) {
if (controller.selectedRunId != null) controller.back();
} else if (controller.selectedRunId != id) {
controller.select(id);
}
}
}
/// Rebuild the switch only when the selection changes. Detail progress and
/// live updates are already watched by [RunDetailView] and [RunsList], so
/// this avoids a second whole-detail rebuild per notification.
void _selectionChanged() {
final selected = controller.selectedRunId;
if (selected == _shownRunId) return;
_shownRunId = selected;
if (mounted) setState(() {});
}
void _select(num id) {
controller.select(id);
widget.onRunSelected?.call(id.toInt());
}
void _back() {
controller.back();
widget.onBack?.call();
}
@override
void dispose() {
controller.removeListener(_changed);
controller.removeListener(_selectionChanged);
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final isCupertino = Theme.of(context).platform == TargetPlatform.iOS;
final selected = _selectedRunId != null;
final content = Stack(
final selected = controller.selectedRunId != null;
return Stack(
children: [
Offstage(
offstage: selected,
child: RunsList(controller: controller, onSelected: (id) {
setState(() => _selectedRunId = id);
controller.select(id);
}),
),
if (selected)
RunDetailView(
controller: controller,
onBack: () {
controller.back();
setState(() => _selectedRunId = null);
},
AnimatedBuilder(
animation: controller,
builder: (context, _) => Offstage(
offstage: selected,
child: RunsList(controller: controller, onSelected: _select),
),
),
if (selected) RunDetailView(controller: controller, onBack: _back),
],
);
if (isCupertino) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text(selected ? 'Run ${controller.detail?['id'] ?? _selectedRunId}' : 'Runs'),
leading: selected ? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: () { controller.back(); setState(() => _selectedRunId = null); },
child: const Text('Runs'),
) : null,
),
child: SafeArea(child: content),
);
}
return content;
}
}
@@ -36,7 +36,7 @@ Widget buildCupertinoRunDetail({
children: [
const Icon(CupertinoIcons.back),
const SizedBox(width: 4),
const Text('Runs'),
const Text('Back'),
],
),
),
@@ -28,7 +28,7 @@ Widget buildMaterialRunDetail({
child: TextButton.icon(
onPressed: onBack,
icon: const Icon(Icons.arrow_back),
label: const Text('Runs'),
label: const Text('Back to list'),
),
),
Text(detailTitle(run), style: theme.textTheme.headlineSmall),
+15 -24
View File
@@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/adaptive/host.dart';
import 'run_detail_content.dart';
import 'run_detail_cupertino.dart';
import 'run_detail_material.dart';
@@ -29,7 +30,7 @@ class _RunDetailViewState extends State<RunDetailView> {
Widget build(BuildContext context) => AnimatedBuilder(
animation: widget.controller,
builder: (context, _) {
final cupertino = _usesCupertino(context);
final cupertino = usesCupertinoHost(context);
final run = widget.controller.detail;
if (run == null) return _placeholder(context, cupertino: cupertino);
final prompt = detailPrompt(run);
@@ -57,34 +58,24 @@ class _RunDetailViewState extends State<RunDetailView> {
},
);
/// CupertinoApp supplies CupertinoLocalizations only, while MaterialApp
/// supplies MaterialLocalizations. This distinguishes the two hosts without
/// assuming a desktop browser's target platform.
bool _usesCupertino(BuildContext context) =>
Localizations.of<MaterialLocalizations>(context, MaterialLocalizations) ==
null;
Widget _placeholder(BuildContext context, {required bool cupertino}) {
if (widget.controller.detailLoading) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
final loading = widget.controller.detailLoading;
final message = loading
? 'Loading run details…'
: widget.controller.error ?? 'Run details unavailable.';
// Back stays available while the detail is pending as well as after a
// failure, so a slow or refused request can never trap the destination.
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (loading) ...[
if (cupertino)
const CupertinoActivityIndicator()
else
const CircularProgressIndicator(),
const SizedBox(height: 12),
const Text('Loading run details…'),
],
),
);
}
final message = widget.controller.error ?? 'Run details unavailable.';
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Text(message, textAlign: TextAlign.center),
@@ -93,12 +84,12 @@ class _RunDetailViewState extends State<RunDetailView> {
if (cupertino)
CupertinoButton(
onPressed: widget.onBack,
child: const Text('Back to runs'),
child: const Text('Back to list'),
)
else
FilledButton(
onPressed: widget.onBack,
child: const Text('Back to runs'),
child: const Text('Back to list'),
),
],
),
@@ -61,6 +61,16 @@ class RunsController extends ChangeNotifier {
if (initialId != null) await select(initialId);
}
/// Re-reads the list and the open detail after the socket was replaced.
///
/// The selection is kept, so a reconnect refreshes in place instead of
/// discarding the detail the operator had open.
Future<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();
+7 -11
View File
@@ -1,8 +1,8 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/run_models.dart';
import 'runs_controller.dart';
@@ -16,15 +16,11 @@ class RunsList extends StatelessWidget {
final RunsController controller;
final ValueChanged<num> onSelected;
bool get _isCupertino =>
defaultTargetPlatform == TargetPlatform.iOS ||
defaultTargetPlatform == TargetPlatform.macOS;
@override
Widget build(BuildContext context) {
if (controller.loading && controller.runs.isEmpty) {
return Center(
child: _isCupertino
child: usesCupertinoHost(context)
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
);
@@ -43,7 +39,7 @@ class RunsList extends StatelessWidget {
if (controller.error != null) _inlineError(context),
Padding(
padding: const EdgeInsets.all(16),
child: _isCupertino
child: usesCupertinoHost(context)
? CupertinoSearchTextField(
placeholder: 'Filter runs',
onChanged: controller.setQuery,
@@ -76,7 +72,7 @@ class RunsList extends StatelessWidget {
children: [
Text(controller.error!),
const SizedBox(height: 8),
_isCupertino
usesCupertinoHost(context)
? CupertinoButton(
onPressed: controller.load,
child: const Text('Retry'),
@@ -94,7 +90,7 @@ class RunsList extends StatelessWidget {
child: Row(
children: [
Expanded(child: Text(controller.error!)),
if (_isCupertino)
if (usesCupertinoHost(context))
CupertinoButton(
onPressed: controller.load,
child: const Text('Retry'),
@@ -106,7 +102,7 @@ class RunsList extends StatelessWidget {
);
Widget _selectors(BuildContext context) {
if (_isCupertino) {
if (usesCupertinoHost(context)) {
return Wrap(
spacing: 8,
children: [
@@ -206,7 +202,7 @@ class RunsList extends StatelessWidget {
final title = identity.label.isEmpty ? 'Run $id' : identity.label;
final subtitle =
'${run['name'] ?? 'Pipeline unavailable'} · ${run['created_at'] ?? 'Time unavailable'}${run['scheduled'] == true ? ' · Scheduled' : ''}';
if (_isCupertino) {
if (usesCupertinoHost(context)) {
return CupertinoListTile(
title: Text(title),
subtitle: Text(subtitle),
+3 -36
View File
@@ -1,40 +1,7 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'shell/adaptive_shell.dart';
import 'shell/destination.dart';
import 'application/bootstrap.dart';
export 'application/app.dart' show MyApp;
export 'shell/adaptive_shell.dart';
export 'shell/destination.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key, this.destinationBodies = const {}, this.cupertino});
final Map<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),
);
}
}
void main() => runPipelinesApp();
+29 -3
View File
@@ -8,20 +8,46 @@ class AdaptiveShell extends StatefulWidget {
super.key,
this.destinationBodies = const {},
this.cupertino = false,
this.destination,
this.onDestinationSelected,
});
final Map<AppDestination, WidgetBuilder> destinationBodies;
final bool cupertino;
/// The destination a route owner selected. When null the shell keeps its own
/// selection, which preserves the plain-shell tests and native composition.
final AppDestination? destination;
final ValueChanged<AppDestination>? onDestinationSelected;
@override
State<AdaptiveShell> createState() => _AdaptiveShellState();
}
class _AdaptiveShellState extends State<AdaptiveShell> {
AppDestination _selected = AppDestination.pipelines;
late AppDestination _selected;
void _select(AppDestination destination) =>
setState(() => _selected = destination);
@override
void initState() {
super.initState();
_selected = widget.destination ?? AppDestination.pipelines;
}
@override
void didUpdateWidget(covariant AdaptiveShell oldWidget) {
super.didUpdateWidget(oldWidget);
final destination = widget.destination;
if (destination != null) _selected = destination;
}
void _select(AppDestination destination) {
final callback = widget.onDestinationSelected;
if (callback != null) {
callback(destination);
return;
}
setState(() => _selected = destination);
}
List<T> _items<T>(T Function(AppDestination) build) =>
AppDestination.values.map(build).toList();
+10
View File
@@ -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;