import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; import '../core/api_gateway.dart'; import '../core/transport/pipelines_client.dart'; import '../shell/adaptive_shell.dart'; import '../shell/destination.dart'; import '../features/attention/notify/notification_controller.dart'; import '../features/attention/notify/chat_question_notices.dart'; import '../features/attention/notify/notification_store.dart'; import '../features/attention/runtime/attention_controller.dart'; import '../features/attention/runtime/attention_store.dart'; import '../features/runs/ui/run_search_selection.dart'; import '../features/search/domain/search_target.dart'; import '../features/settings/settings_screen.dart'; import 'app.dart'; import 'app_route.dart'; import 'app_router.dart'; import 'app_session.dart'; import 'chat_destination.dart'; import 'pipelines_destination.dart'; import 'runs_destination.dart'; import 'schedules_destination.dart'; import 'search_destination.dart'; import 'server_endpoint.dart'; import 'templates_destination.dart'; /// The application's return-to-foreground policy for the shared socket. /// /// Only a socket the client dropped (disconnected) is reopened. Idle is a /// deliberate Disconnect the operator made, so returning never undoes it, and /// connected/connecting already have their own answer — foregrounding neither /// churns a live socket nor restarts an attempt already in flight. bool shouldReconnectOnForeground(ConnectionKind kind) => kind == ConnectionKind.disconnected; /// Composes the live application around one [AppSession] and one [Router]. /// /// Tests may inject the client and route-information provider; the session /// owns the socket either way, so there is never a second app-level connection. class PipelinesApp extends StatefulWidget { const PipelinesApp({ super.key, required this.server, this.client, this.cupertino, this.routeInformationProvider, }); final ServerEndpoint server; final PipelinesClient? client; final bool? cupertino; /// Test seam: the Router's initial and subsequent route information. final RouteInformationProvider? routeInformationProvider; @override State createState() => _PipelinesAppState(); } class _PipelinesAppState extends State with WidgetsBindingObserver { late final AppSession _session; late final AppRouterDelegate _delegate; late final RouteInformationProvider _provider; late final bool _ownsProvider; late final RouterConfig _config; late final bool _cupertino; /// Advances when a template create is accepted. The Pipelines destination /// uses it to re-read through its mounted controller; no row is inserted /// locally, so the next list reply is the only source of the new pipeline. int _pipelinesRefresh = 0; /// Advances when a launch was accepted. The Runs destination re-reads its /// list once; the run itself is then opened from its route. int _runsRefresh = 0; /// Prevents duplicate resumed notifications from refreshing twice before /// the next background transition starts another foreground visit. bool _foregroundVisitHandled = false; /// One run detail request from Search, delivered through the shell so the /// mounted run detail can resolve it once the named run's steps have loaded. /// A field or artifact hit names no addressable URL of its own, so the request /// is not route state; it is cleared after the detail applies it or when the /// shell leaves that run, so an abandoned hit never replays later. RunSearchSelection? _pendingRunSearch; /// One notification capability for the app: the Runs attention surface /// publishes live transitions and Settings renders the same permission. late final NotificationController _notifications = NotificationController( store: const SharedPreferencesNotificationStore(), ); ChatQuestionNotices? _chatQuestionNotices; /// One attention surface for the app: the Runs heading's bell draws from it /// and the shell mirrors its count on the Runs tab, so the badge is visible /// from every destination. The Runs list seeds the rows when it loads; pushed /// `run_event` frames are folded here so the count moves while another /// destination is shown, and a replaced socket drops the status baseline. late final AttentionController _attention = AttentionController( store: const SharedPreferencesAttentionStore(), ); StreamSubscription? _attentionFrames; int _attentionEpoch = 0; /// The count the shell's Runs tab shows; only a changed count rebuilds it. final ValueNotifier _attentionCount = ValueNotifier(0); @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _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. // The comparison includes the query: `?visit=N` is part of the route, while // a dropped or unknown query is canonicalised away. final location = routeLocation(_provider.value.uri); final initial = AppRoute.parse(location); if (location != initial.path) { _provider.routerReportsNewRouteInformation( RouteInformation(uri: Uri.parse(initial.path)), type: RouteInformationReportingType.neglect, ); } _cupertino = widget.cupertino ?? _platformIsCupertino; _notifications.onOpenRun = (id) => _delegate.goTo(AppRoute.run(id)); unawaited(_notifications.load()); unawaited(_attention.load()); _attentionFrames = _session.gateway.frames .where((frame) => frame['type'] == 'run_event') .listen(_attention.observeFrame); _session.addListener(_attentionSessionChanged); _attention.addListener(_attentionChanged); _delegate = AppRouterDelegate( initial: initial, cupertino: _cupertino, onPopToRuns: () => _delegate.goTo(AppRoute.runs), onPopToChat: () => _delegate.goTo(AppRoute.chat), templatesBuilder: _buildTemplates, schedulesBuilder: _buildSchedules, builder: _buildShell, ); _delegate.addListener(_routeChanged); _tabRoutes[_destinationOf(_delegate.shellRoute.kind)] = _delegate.shellRoute; _chatQuestionNotices = ChatQuestionNotices( gateway: _session.gateway, canNotify: () => _notifications.canNotify, activeChatSessionId: () { final route = _delegate.shellRoute; return route.kind == AppRouteKind.chat ? route.chatSessionId : null; }, sessionTitle: _chatSessionTitle, openChat: (id) => _delegate.goTo(AppRoute.chatSession(id)), bridge: _notifications.bridge, ); _config = RouterConfig( routeInformationParser: const AppRouteParser(), routerDelegate: _delegate, routeInformationProvider: _provider, ); unawaited(_session.start()); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); _session.removeListener(_attentionSessionChanged); unawaited(_attentionFrames?.cancel()); _attention.removeListener(_attentionChanged); _attention.dispose(); _attentionCount.dispose(); _notifications.dispose(); _chatQuestionNotices?.dispose(); _delegate.removeListener(_routeChanged); _delegate.dispose(); if (_ownsProvider) { (_provider as PlatformRouteInformationProvider).dispose(); } _session.dispose(); super.dispose(); } /// Returning to the foreground recovers a socket the client dropped while /// the app was hidden. A deliberate Disconnect reaches idle and is left /// alone, and a connected or connecting socket is not churned: only the /// disconnected state reopens the validated endpoint now, cancelling the /// pending backoff delay. The session's connected transition then re-sends /// the send-only run watch (and Settings re-pings for its build/protocol /// facts), so no screen re-subscribes on its own. @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state != AppLifecycleState.resumed) { _foregroundVisitHandled = false; return; } if (_foregroundVisitHandled) return; _foregroundVisitHandled = true; final connection = _session.connection.kind; if (shouldReconnectOnForeground(connection)) { unawaited(_session.retry()); return; } if (connection != ConnectionKind.connected) return; // A return to the foreground refreshes only the visible list. Detail routes // (including pipeline definitions and run visits) keep their current data. if (_delegate.hasTransientRoute || _isEditingText) return; final route = _delegate.route; if (route.kind == AppRouteKind.pipelines && route.pipelineId == null && route.stageKey == null) { setState(() => _pipelinesRefresh++); } else if (route.kind == AppRouteKind.runs && route.runId == null) { setState(() => _runsRefresh++); } } bool get _isEditingText { final focusContext = FocusManager.instance.primaryFocus?.context; return focusContext?.findAncestorWidgetOfExactType() != null; } /// A replaced socket drops the attention status baseline so the gap cannot /// replay a transition; the Runs list's next read reseeds the rows. void _attentionSessionChanged() { final epoch = _session.connectionEpoch; if (epoch == _attentionEpoch) return; _attentionEpoch = epoch; _attention.resetForReconnect(); } /// Mirrors the controller's entry count for the shell. The Runs list seeds /// the rows from inside its own build, and the shell sits above that layout /// scope, so a count that changes mid-build lands after the frame; a pushed /// frame arrives outside any build and applies at once. void _attentionChanged() { if (!mounted) return; final count = _attention.entries.length; if (count == _attentionCount.value) return; if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) { SchedulerBinding.instance.addPostFrameCallback( (_) => _attentionChanged(), ); return; } _attentionCount.value = count; } @override Widget build(BuildContext context) => MyApp.router(cupertino: _cupertino, routerConfig: _config); /// Open a result through the exact identity the hit records. An unresolvable /// hit navigates nowhere: the screen already presents it read-only rather than /// guessing a destination. /// /// A field or artifact hit has no URL of its own: both open the run and leave /// a resolved-once request for the mounted detail, which selects the recorded /// Summary section or visit as soon as that run's steps are available. A /// sequence or field the run did not record leaves the plain detail. void _openSearchResult(JsonMap hit) { final resolved = searchTargetFor(hit); if (resolved is! ResolvedSearchTarget) return; AppRoute? route; RunSearchSelection? selection; switch (resolved.target) { case SearchPipelineTarget(:final pipelineId): route = AppRoute.pipeline(pipelineId); case SearchVersionTarget(:final pipelineId, :final version): route = AppRoute.pipeline(pipelineId, version: version); case SearchRunTarget(:final runId): route = AppRoute.run(runId); case SearchStepTarget(:final runId, :final stage, :final visit): // The server records a 1-based visit number; the route's `visit` is the // zero-based index into the recorded timeline. final index = visit == null || visit < 1 ? null : visit - 1; route = stage == null ? AppRoute.run(runId) : AppRoute.run.stage(runId, stage, visit: index); case SearchFieldTarget(:final runId, :final sequence, :final field): selection = RunSearchSelection( runId: runId, sequence: sequence, field: field, ); route = AppRoute.run(runId); case SearchArtifactTarget(:final runId, :final sequence): if (runId != null) { selection = RunSearchSelection(runId: runId, sequence: sequence); route = AppRoute.run(runId); } } if (route == null) return; setState(() => _pendingRunSearch = selection); _delegate.goTo(route); } /// The mounted run detail applied the pending request; reopening the same run /// later starts from its plain detail and never replays the search selection. void _runSearchConsumed() { if (!mounted || _pendingRunSearch == null) return; setState(() => _pendingRunSearch = null); } /// Drops a pending request once the shell leaves the run it names. /// /// The mounted detail is the only consumer, and it exists only after the run's /// detail has loaded. Backing out while that read is still pending, or leaving /// a failed detail, would otherwise keep the request for the next unrelated /// visit to the same run. Search/Templates/Schedules pages above the run keep /// it, because the shell route underneath them still names that run. /// The last route each tab showed, so switching tabs returns to where the /// operator left it; tapping the open tab again goes to its root. final Map _tabRoutes = {}; void _selectDestination(AppDestination destination) { final current = _destinationOf(_delegate.shellRoute.kind); final last = _tabRoutes[destination]; _delegate.goTo( destination == current || last == null ? _routeOf(destination) : last, ); } void _routeChanged() { final shown = _delegate.shellRoute; _tabRoutes[_destinationOf(shown.kind)] = shown; final pending = _pendingRunSearch; if (!mounted || pending == null) return; final route = _delegate.shellRoute; if (route.kind == AppRouteKind.runs && route.runId == pending.runId) return; setState(() => _pendingRunSearch = null); } Future _chatSessionTitle(String id) async { final reply = await _session.gateway.call('chat_sessions'); final sessions = reply['chat_sessions']; if (sessions is! List) return null; for (final value in sessions) { if (value is Map && value['id'] == id) return '${value['title'] ?? ''}'; } return null; } /// The Templates page above Settings. Closing it restores the same Settings /// screen instance, so an edited field or an open connection state survives. Widget _buildSchedules(BuildContext context) => SchedulesDestination( session: _session, server: widget.server, onBack: _delegate.closeSchedules, onOpenPipeline: (id) => _delegate.goTo(AppRoute.pipeline(id)), ); Widget _buildTemplates(BuildContext context) => TemplatesDestination( session: _session, server: widget.server, onBack: _delegate.closeTemplates, onCreated: _templateCreated, initialKey: _delegate.route.templateKey, ); /// An accepted create only invalidates Pipelines; the list is re-read and the /// new row appears from the server's reply, never from an optimistic insert. void _templateCreated(JsonMap _) { if (!mounted) return; setState(() => _pipelinesRefresh++); } /// Opens the run id an accepted launch named and invalidates the Runs list. /// /// The order is deliberate: the list token is already advanced when the Runs /// screen mounts for the first time, so it performs one fresh `list_runs` /// read and then opens the route's run. No row is inserted locally. void _runStarted(int id) { if (!mounted) return; setState(() => _runsRefresh++); _delegate.goTo(AppRoute.run(id)); } /// The shell rebuilds its Runs tab badge from the attention count alone; the /// destination bodies keep their state through it. Widget _buildShell(BuildContext context, AppRoute route) => ValueListenableBuilder( valueListenable: _attentionCount, builder: (context, count, _) => _shellFor(route, count), ); Widget _shellFor(AppRoute route, int attentionCount) { // Each tab is built from the route it last showed, so switching tabs keeps // an open run, pipeline or chat instead of resetting it. AppRoute tab(AppDestination destination) => _destinationOf(route.kind) == destination ? route : _tabRoutes[destination] ?? _routeOf(destination); final pipelinesRoute = tab(AppDestination.pipelines); final runsRoute = tab(AppDestination.runs); final chatRoute = tab(AppDestination.chat); return AdaptiveShell( attentionCount: attentionCount, detailOpen: route.runId != null || route.chatSessionId != null || (route.kind == AppRouteKind.pipelines && route.pipelineId != null), cupertino: _cupertino, destination: _destinationOf(route.kind), onDestinationSelected: _selectDestination, destinationBodies: { AppDestination.pipelines: (_) => PipelinesDestination( session: _session, server: widget.server, refreshToken: _pipelinesRefresh, onRunStarted: _runStarted, onViewPipelineRuns: (id) => _delegate.goTo(AppRoute.runsForPipeline(id)), onOpenSchedules: _delegate.openSchedules, initialPipelineId: pipelinesRoute.pipelineId, initialVersion: pipelinesRoute.version, initialStageKey: pipelinesRoute.stageKey, ), // The one place a field or artifact hit's selection can be resolved: the // run detail owns the recorded visit and Summary section. AppDestination.runs: (_) => RunSearchSelectionScope( selection: _pendingRunSearch, onConsumed: _runSearchConsumed, child: RunsDestination( session: _session, server: widget.server, initialRunId: runsRoute.runId, initialPipelineId: runsRoute.pipelineId, initialStageKey: runsRoute.stageKey, initialVisit: runsRoute.visit, initialDecide: runsRoute.decide, listRefreshToken: _runsRefresh, notifications: _notifications, attention: _attention, onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)), onBack: (id) => _delegate.goTo( id == null ? AppRoute.runs : AppRoute.runsForPipeline(id), ), onPipelineFilterChanged: (id) => _delegate.goTo( id == null ? AppRoute.runs : AppRoute.runsForPipeline(id), ), onOpenPipeline: (id, version) => _delegate.goTo(AppRoute.pipeline(id, version: version)), ), ), AppDestination.chat: (_) => ChatDestination( session: _session, server: widget.server, initialSessionId: chatRoute.chatSessionId, onSessionSelected: (id) => _delegate.goTo(AppRoute.chatSession(id)), onBack: () => _delegate.goTo(AppRoute.chat), ), // Search is the fifth tab; a result opens its destination. AppDestination.search: (_) => SearchDestination( session: _session, server: widget.server, onOpen: _openSearchResult, embedded: true, ), AppDestination.settings: (_) => SettingsScreen( client: _session.client, // A phone signs in at the web login; a browser has its own. showSignIn: !kIsWeb, showAndroidDownload: kIsWeb, initialEndpoint: _session.endpoint, embedded: true, onOpenTemplates: _delegate.openTemplates, notifications: _notifications, ), }, ); } AppDestination _destinationOf(AppRouteKind kind) => switch (kind) { AppRouteKind.pipelines => AppDestination.pipelines, AppRouteKind.runs => AppDestination.runs, AppRouteKind.chat => AppDestination.chat, AppRouteKind.search => AppDestination.search, AppRouteKind.settings => AppDestination.settings, // Templates and Schedules are Settings sub-pages, not a fifth tab. AppRouteKind.templates => AppDestination.settings, AppRouteKind.schedules => AppDestination.settings, }; AppRoute _routeOf(AppDestination destination) => switch (destination) { AppDestination.pipelines => AppRoute.pipelines, AppDestination.runs => AppRoute.runs, AppDestination.chat => AppRoute.chat, AppDestination.search => AppRoute.search, AppDestination.settings => AppRoute.settings, }; bool get _platformIsCupertino => defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS; }