import 'dart:async'; import 'package:flutter/widgets.dart'; import '../../core/api_gateway.dart'; import '../../shell/destination.dart'; import '../../shell/detail_page.dart'; import '../../shell/empty_detail_pane.dart'; import '../../shell/list_detail.dart'; import '../attention/notify/notification_controller.dart'; import '../../ui/layout/content_width.dart'; import '../attention/runtime/attention_controller.dart'; import '../attention/runtime/attention_store.dart'; import '../pipelines/pending_run_store.dart'; import '../pipelines/pipeline_repository.dart'; import '../pipelines/pipelines_controller.dart'; import 'actions/decision_action.dart'; import 'data/runs_repository.dart'; import 'data/runs_sort_store.dart'; import 'domain/run_decisions.dart'; import 'ui/new_run_button.dart'; import 'ui/new_run_flow.dart'; import 'ui/run_pipeline_link.dart'; import 'ui/run_detail_view.dart'; import 'ui/run_search_selection.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.initialPipelineId, this.initialStageKey, this.initialVisit, this.initialDecide = false, this.syncToken = 0, this.listRefreshToken = 0, this.onRunSelected, this.onBack, this.onPipelineFilterChanged, this.onOpenPipeline, this.attentionStore = const SharedPreferencesAttentionStore(), this.attentionNow, this.notifications, this.attention, this.sortStore = const SharedPreferencesRunsSortStore(), this.pendingRunStore = const SharedPreferencesPendingRunStore(''), this.onOpenInChat, this.onSendToChat, }); final ApiGateway gateway; /// The run the current route names, or null for the list. final int? initialRunId; final int? initialPipelineId; /// The recorded stage visit the route names inside [initialRunId]. The detail /// applies it once per route target; the feature never invents a visit. final String? initialStageKey; final int? initialVisit; /// The route's `?action=decide`: once the named run's detail is loaded, open /// the recorded decision prompt when the run is genuinely waiting. Consumed /// once per route target, so a rebuild or a live re-read never reopens it. final bool initialDecide; /// Advances when the shared socket is replaced. The loaded screen refreshes /// in place instead of being remounted, so its selection survives. final int syncToken; /// Advances when a launch accepted outside this screen must be reflected by a /// fresh `list_runs` read. It never inserts a row of its own. final int listRefreshToken; final ValueChanged? onRunSelected; final ValueChanged? onBack; final ValueChanged? onPipelineFilterChanged; /// Opens a pipeline from the run detail's pipeline name. final OpenPipeline? onOpenPipeline; /// Persisted attention dismissals and the clock for its local-day window. /// The app uses SharedPreferences; tests and fixtures inject a memory store. final AttentionStore attentionStore; final DateTime Function()? attentionNow; /// App-level notification delivery for live attention transitions. final NotificationController? notifications; /// The app's shared attention controller, mirrored on the shell's Runs tab. final AttentionController? attention; /// Where the list's sort choice persists; tests inject a memory store. final RunsSortStore sortStore; /// Where a New run's pending launch intent persists, under the same endpoint /// scope the Pipelines tab uses. Tests inject a memory store. final PendingRunStore pendingRunStore; final Future Function(BuildContext, JsonMap)? onOpenInChat; final Future Function(BuildContext, JsonMap, String)? onSendToChat; @override State createState() => _RunsScreenState(); } /// The vertical band the New run button occupies over the list's bottom edge: /// its margin, the extended button's height and its margin again. const double _newRunBand = 88; class _RunsScreenState extends State { late final RunsController controller; /// Starts a run from the New run picker. Its state is only the pending /// launch intent; the pipeline itself is read when the operator picks one. late final PipelinesController _launches; num? _shownRunId; int? _reportedPipelineId; bool _applyingRoutePipeline = false; /// The route's decision request is one-shot: the first loaded detail for the /// named run consumes it, whether or not that run is waiting. bool _decideConsumed = false; /// The open run is its own page over the tabs. final DetailPageHost _page = DetailPageHost(); @override void initState() { super.initState(); controller = RunsController( RunsRepository(widget.gateway), sortStore: widget.sortStore, ); _launches = PipelinesController( PipelinesRepository(widget.gateway), pendingRunStore: widget.pendingRunStore, ); // A deleted open run closes its detail; the route returns to the list. controller.onOpenRunRemoved = () => widget.onBack?.call(controller.pipelineId); _reportedPipelineId = widget.initialPipelineId; if (widget.initialPipelineId != null) { controller.clearFilters(); controller.setPipeline(widget.initialPipelineId); } controller.listen(widget.gateway.frames); controller.addListener(_selectionChanged); controller.addListener(_pipelineFilterChanged); controller.addListener(_detailChanged); controller.load(widget.initialRunId); } @override void didUpdateWidget(covariant RunsScreen oldWidget) { super.didUpdateWidget(oldWidget); if (widget.initialRunId != oldWidget.initialRunId || widget.initialDecide != oldWidget.initialDecide) { _decideConsumed = false; } if (widget.initialPipelineId != oldWidget.initialPipelineId) { final id = widget.initialPipelineId; // A run detail replaces the list URL but retains its active list filter. // Only a route back to the list can explicitly clear that facet. if (id != null || widget.initialRunId == null) { _applyingRoutePipeline = true; try { if (id != null) controller.clearFilters(); controller.setPipeline(id); _reportedPipelineId = id; } finally { _applyingRoutePipeline = false; } } } // Both reconnect and foreground/launch invalidation refresh the retained // selection as well as the list. Coalesce tokens delivered in one rebuild. if (widget.syncToken != oldWidget.syncToken || widget.listRefreshToken != oldWidget.listRefreshToken) { 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); } } if (widget.initialRunId != oldWidget.initialRunId || widget.initialDecide != oldWidget.initialDecide) { _detailChanged(); } } /// 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 _pipelineFilterChanged() { final id = controller.pipelineId; if (_applyingRoutePipeline) { _reportedPipelineId = id; return; } if (id == _reportedPipelineId) return; _reportedPipelineId = id; if (controller.selectedRunId == null) { widget.onPipelineFilterChanged?.call(id); } } /// Opens the route's decision prompt after the named detail has arrived. /// A non-waiting run consumes the request without a prompt, and the prompt /// itself only closes; the detail underneath is left as it is. void _detailChanged() { if (!widget.initialDecide || _decideConsumed) return; final run = controller.detail; final selected = controller.selectedRunId; if (run == null || selected == null || run['id'] != selected) return; _decideConsumed = true; if (pendingDecision(run) == null) return; WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted || controller.selectedRunId != selected) return; final current = controller.detail; if (current == null || pendingDecision(current) == null) return; unawaited( showRunDecisionPrompt( context: context, run: current, gateway: widget.gateway, onRunChanged: controller.acceptRunDetail, isCurrent: () => mounted && controller.selectedRunId == selected, ), ); }); } void _select(num id) { controller.select(id); widget.onRunSelected?.call(id.toInt()); } void _back() { controller.back(); widget.onBack?.call(controller.pipelineId); } /// The New run picker, then the same start flow a pipeline's Run opens. void _startNewRun() => unawaited( startNewRunFlow( context: context, controller: _launches, gateway: widget.gateway, onRunStarted: _newRunStarted, ), ); /// An accepted launch re-reads the list so its row appears, then opens the /// run the same way a row tap does. void _newRunStarted(int id) { unawaited(controller.resync()); _select(id); } @override void dispose() { controller.removeListener(_selectionChanged); controller.removeListener(_pipelineFilterChanged); controller.removeListener(_detailChanged); _page.dispose(); controller.dispose(); _launches.dispose(); super.dispose(); } /// The shell's pending search selection, read in [build] so this screen /// rebuilds (and refreshes an open detail page) whenever it changes. RunSearchSelectionScope? _searchScope; /// The run detail, under the shell's search selection. /// /// On a narrow window the detail is its own page on the app's navigator, so /// it is not a descendant of the shell's [RunSearchSelectionScope]; relaying /// the scope keeps a field or artifact hit's selection reachable there too. Widget _detail(VoidCallback onBack) { final view = RunDetailView( controller: controller, gateway: widget.gateway, onBack: onBack, onRunOpened: _select, onOpenPipeline: widget.onOpenPipeline, onOpenInChat: widget.onOpenInChat, onSendToChat: widget.onSendToChat == null ? null : (context, run, draft) => widget.onSendToChat!(context, run, draft), initialStageKey: widget.initialStageKey, initialVisit: widget.initialVisit, ); final scope = _searchScope; if (scope == null) return view; return RunSearchSelectionScope( selection: scope.selection, onConsumed: scope.onConsumed, child: view, ); } @override Widget build(BuildContext context) { _searchScope = RunSearchSelectionScope.maybeOf(context); final selected = controller.selectedRunId != null; // The same adaptive list/detail layout as Pipelines and Chat. final narrow = !showsListBesideDetail(context); _page.sync( context, selected: selected && narrow, destination: AppDestination.runs, onClosed: _back, builder: (context) => _detail(() => Navigator.of(context).maybePop()), ); // The New run button floats over the list's bottom-right corner while the // list is the visible view. The list reserves the button's band in its // bottom padding, so its last row rests above the button, and the overlay // lifts clear of the shell's bar like the list's own clearance does. final list = Stack( fit: StackFit.expand, children: [ AnimatedBuilder( animation: controller, builder: (context, _) { final showsButton = !(narrow && selected); final media = MediaQuery.of(context); return MediaQuery( data: media.copyWith( padding: media.padding.copyWith( bottom: media.padding.bottom + (showsButton ? _newRunBand : 0), ), ), child: ContentWidth( child: RunsList( active: narrow ? !selected : true, controller: controller, onSelected: _select, syncToken: widget.syncToken, attentionStore: widget.attentionStore, attentionNow: widget.attentionNow, notifications: widget.notifications, attention: widget.attention, onOpenInChat: widget.onOpenInChat, ), ), ); }, ), AnimatedBuilder( animation: controller, builder: (context, _) => narrow && selected ? const SizedBox.shrink() : Positioned( left: 16, right: 16, bottom: 16 + MediaQuery.paddingOf(context).bottom, child: Align( alignment: AlignmentDirectional.bottomEnd, child: NewRunButton(onPressed: _startNewRun), ), ), ), ], ); if (narrow) return list; return ListDetailPanes( list: list, detailIdentity: controller.selectedRunId, detail: selected ? DetailPane( key: const ValueKey('run-detail-pane'), destination: AppDestination.runs, implyBack: false, builder: (_) => _detail(_back), ) : const EmptyDetailPane( destination: AppDestination.runs, message: 'Select a run to open it here.', ), ); } }