merge(app): finish retained Runs integration after deadline

This commit is contained in:
2026-10-21 17:26:41 +01:00
40 changed files with 5025 additions and 50 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)
+113
View File
@@ -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();
}
}
+243
View File
@@ -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
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;