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);
}
}
}