From 9344e6d3c05164390cd00b0895595ac3b8dc39b2 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 11:52:22 +0100 Subject: [PATCH] feat(app): open a run's decision prompt from its URL A /runs/:id?action=decide route now opens the landed decision prompt once the named detail loads, and only when that detail genuinely awaits a person. A non-waiting run consumes the request without inventing a prompt, and dismissing the prompt leaves the loaded detail. The route flag is forwarded through the existing destination seam; submission, refusal wording and the bounded re-read are shared with the detail's Decide button. --- app/lib/application/pipelines_app.dart | 1 + app/lib/application/runs_destination.dart | 6 + .../runs/actions/decision_action.dart | 184 +++++++++++------- app/lib/features/runs/screen.dart | 52 +++++ .../runs/ui/run_decide_deep_link_test.dart | 156 +++++++++++++++ 5 files changed, 328 insertions(+), 71 deletions(-) create mode 100644 app/test/features/runs/ui/run_decide_deep_link_test.dart diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 524dbf78..321be5a9 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -223,6 +223,7 @@ class _PipelinesAppState extends State { initialRunId: route.runId, initialStageKey: route.stageKey, initialVisit: route.visit, + initialDecide: route.decide, listRefreshToken: _runsRefresh, notifications: _notifications, onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)), diff --git a/app/lib/application/runs_destination.dart b/app/lib/application/runs_destination.dart index e5270d88..978faad1 100644 --- a/app/lib/application/runs_destination.dart +++ b/app/lib/application/runs_destination.dart @@ -21,6 +21,7 @@ class RunsDestination extends StatelessWidget { this.initialRunId, this.initialStageKey, this.initialVisit, + this.initialDecide = false, this.onRunSelected, this.onBack, this.listRefreshToken = 0, @@ -37,6 +38,10 @@ class RunsDestination extends StatelessWidget { final String? initialStageKey; final int? initialVisit; + /// The route's `?action=decide`. Forwarded as-is; the loaded screen decides + /// from the run's own detail whether a prompt exists. + final bool initialDecide; + final ValueChanged? onRunSelected; final VoidCallback? onBack; @@ -84,6 +89,7 @@ class RunsDestination extends StatelessWidget { initialRunId: initialRunId, initialStageKey: initialStageKey, initialVisit: initialVisit, + initialDecide: initialDecide, syncToken: session.connectionEpoch, listRefreshToken: listRefreshToken, notifications: notifications, diff --git a/app/lib/features/runs/actions/decision_action.dart b/app/lib/features/runs/actions/decision_action.dart index 246c66fb..7635f1c4 100644 --- a/app/lib/features/runs/actions/decision_action.dart +++ b/app/lib/features/runs/actions/decision_action.dart @@ -40,8 +40,6 @@ class HumanDecisionAction extends StatefulWidget { class _HumanDecisionActionState extends State { PendingDecision? _pending; bool _dialogOpen = false; - bool _sending = false; - Future? _resync; @override void initState() { @@ -69,11 +67,13 @@ class _HumanDecisionActionState extends State { if (decision == null || _dialogOpen) return; _dialogOpen = true; try { - await showHumanDecisionPrompt( + await showRunDecisionPrompt( context: context, - decision: decision, + run: widget.run, + gateway: widget.gateway, cupertino: _usesCupertino(context), - onSubmit: (draft) => _submit(decision, draft), + onRunChanged: _acceptRun, + isCurrent: () => _owns(decision.runId), ); } finally { _dialogOpen = false; @@ -81,76 +81,14 @@ class _HumanDecisionActionState extends State { } } - Future _submit( - PendingDecision decision, - DecisionDraft draft, - ) async { - final option = draft.selected?.trim() ?? ''; - if (option.isEmpty) return const ActionRefusal(actionOptionRequired); - if (_sending) return const ActionRefusal(actionAlreadySending); - _sending = true; - final repository = RunsRepository(widget.gateway); - try { - final JsonMap run; - try { - run = await repository.decideRun( - decision.runId, - stage: decision.stageKey, - option: option, - feedback: draft.feedback, - ); - } catch (error) { - return ActionRefusal( - _describe(error), - stillPossible: _resyncRun(decision), - ); - } - if (!mounted) return null; - if (_owns(decision.runId)) { - setState(() => _pending = pendingDecision(run)); - widget.onRunChanged(run); - } - return null; - } finally { - _sending = false; - } + void _acceptRun(JsonMap run) { + if (!mounted) return; + setState(() => _pending = pendingDecision(run)); + widget.onRunChanged(run); } bool _owns(num id) => mounted && widget.run['id'] == id; - /// One bounded re-read per refusal. A refusal that arrives while a read is - /// already in flight observes that same read instead of starting another. - Future _resyncRun(PendingDecision decision) { - return _resync ??= _readRun(decision); - } - - Future _readRun(PendingDecision expected) async { - try { - final run = await RunsRepository(widget.gateway).getRun(expected.runId); - if (!_owns(expected.runId)) return null; - final next = pendingDecision(run); - setState(() => _pending = next); - widget.onRunChanged(run); - return _stillDecidable(next, expected); - } catch (_) { - // Unknown server truth: keep the refusal and leave a deliberate retry. - return null; - } finally { - _resync = null; - } - } - - /// Whether the refreshed run offers the same decision the prompt is showing. - bool _stillDecidable(PendingDecision? next, PendingDecision expected) { - if (next == null || - next.runId != expected.runId || - next.stageKey != expected.stageKey) { - return false; - } - final keys = next.options.map((option) => option.key).toSet(); - return expected.options.every((option) => keys.contains(option.key)); - } - @override Widget build(BuildContext context) { final decision = _pending; @@ -170,6 +108,110 @@ class _HumanDecisionActionState extends State { } } +/// Opens the same decision prompt without a button, for a run route whose +/// `?action=decide` asks the detail to continue into the recorded checkpoint. +/// +/// A run that is not genuinely waiting on a person returns immediately, so the +/// deep link never invents a decision. Confirming sends through the same +/// repository call, refusal wording and bounded re-read as +/// [HumanDecisionAction]; [onRunChanged] receives only accepted server detail. +Future showRunDecisionPrompt({ + required BuildContext context, + required JsonMap run, + required ApiGateway gateway, + required ValueChanged onRunChanged, + required bool cupertino, + bool Function()? isCurrent, +}) async { + final decision = pendingDecision(run); + if (decision == null) return; + final submission = _DecisionSubmission( + decision: decision, + gateway: gateway, + onAccepted: onRunChanged, + isCurrent: isCurrent ?? () => true, + ); + await showHumanDecisionPrompt( + context: context, + decision: decision, + cupertino: cupertino, + onSubmit: submission.submit, + ); +} + +/// One prompt's send/refusal state, shared by the button and the deep link. +class _DecisionSubmission { + _DecisionSubmission({ + required this.decision, + required this.gateway, + required this.onAccepted, + required this.isCurrent, + }); + + final PendingDecision decision; + final ApiGateway gateway; + final ValueChanged onAccepted; + final bool Function() isCurrent; + + bool _sending = false; + Future? _resync; + + Future submit(DecisionDraft draft) async { + final option = draft.selected?.trim() ?? ''; + if (option.isEmpty) return const ActionRefusal(actionOptionRequired); + if (_sending) return const ActionRefusal(actionAlreadySending); + _sending = true; + try { + final JsonMap run; + try { + run = await RunsRepository(gateway).decideRun( + decision.runId, + stage: decision.stageKey, + option: option, + feedback: draft.feedback, + ); + } catch (error) { + return ActionRefusal(_describe(error), stillPossible: _resyncRun()); + } + if (!isCurrent()) return null; + onAccepted(run); + return null; + } finally { + _sending = false; + } + } + + /// One bounded re-read per refusal. A refusal that arrives while a read is + /// already in flight observes that same read instead of starting another. + Future _resyncRun() => _resync ??= _readRun(); + + Future _readRun() async { + try { + final run = await RunsRepository(gateway).getRun(decision.runId); + if (!isCurrent()) return null; + final next = pendingDecision(run); + onAccepted(run); + return _stillDecidable(next, decision); + } catch (_) { + // Unknown server truth: keep the refusal and leave a deliberate retry. + return null; + } finally { + _resync = null; + } + } + + /// Whether the refreshed run offers the same decision the prompt is showing. + bool _stillDecidable(PendingDecision? next, PendingDecision expected) { + if (next == null || + next.runId != expected.runId || + next.stageKey != expected.stageKey) { + return false; + } + final keys = next.options.map((option) => option.key).toSet(); + return expected.options.every((option) => keys.contains(option.key)); + } +} + String _describe(Object error) { final message = '$error'; return message.trim().isEmpty ? 'The server refused the decision.' : message; diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index e6ae2c14..3e8403e2 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -1,9 +1,14 @@ +import 'dart:async'; + import 'package:flutter/widgets.dart'; import '../../core/api_gateway.dart'; +import '../../ui/adaptive/host.dart'; import '../attention/notify/notification_controller.dart'; import '../attention/runtime/attention_store.dart'; +import 'actions/decision_action.dart'; import 'data/runs_repository.dart'; +import 'domain/run_decisions.dart'; import 'ui/run_detail_view.dart'; import 'ui/runs_controller.dart'; import 'ui/runs_list.dart'; @@ -21,6 +26,7 @@ class RunsScreen extends StatefulWidget { this.initialRunId, this.initialStageKey, this.initialVisit, + this.initialDecide = false, this.syncToken = 0, this.listRefreshToken = 0, this.onRunSelected, @@ -40,6 +46,11 @@ class RunsScreen extends StatefulWidget { 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; @@ -67,18 +78,27 @@ class _RunsScreenState extends State { late final RunsController controller; num? _shownRunId; + /// 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; + @override void initState() { super.initState(); controller = RunsController(RunsRepository(widget.gateway)); controller.listen(widget.gateway.frames); controller.addListener(_selectionChanged); + 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.syncToken != oldWidget.syncToken) { controller.resync(); } @@ -96,6 +116,10 @@ class _RunsScreenState extends State { controller.select(id); } } + if (widget.initialRunId != oldWidget.initialRunId || + widget.initialDecide != oldWidget.initialDecide) { + _detailChanged(); + } } /// Rebuild the switch only when the selection changes. Detail progress and @@ -108,6 +132,33 @@ class _RunsScreenState extends State { if (mounted) setState(() {}); } + /// 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, + cupertino: usesCupertinoHost(context), + isCurrent: () => mounted && controller.selectedRunId == selected, + ), + ); + }); + } + void _select(num id) { controller.select(id); widget.onRunSelected?.call(id.toInt()); @@ -121,6 +172,7 @@ class _RunsScreenState extends State { @override void dispose() { controller.removeListener(_selectionChanged); + controller.removeListener(_detailChanged); controller.dispose(); super.dispose(); } diff --git a/app/test/features/runs/ui/run_decide_deep_link_test.dart b/app/test/features/runs/ui/run_decide_deep_link_test.dart new file mode 100644 index 00000000..1bebcfe2 --- /dev/null +++ b/app/test/features/runs/ui/run_decide_deep_link_test.dart @@ -0,0 +1,156 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; + +JsonMap _waitingRun() => { + 'id': 9, + 'title': 'Human checkpoint', + 'name': 'fixture', + 'status': 'waiting', + 'executing': false, + 'current_stage': 'gate', + 'graph': { + 'stages': [ + { + 'key': 'gate', + 'type': 'human', + 'edges': {'approve': '#success'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'stage': 'gate', + 'status': 'waiting', + 'output': { + 'prompt': 'Please review this recorded checkpoint.', + 'options': ['approve'], + }, + }, + ], +}; + +JsonMap _finishedRun() => { + ..._waitingRun(), + 'status': 'succeeded', + 'steps': [ + { + 'sequence': 1, + 'stage': 'gate', + 'status': 'completed', + 'outcome': 'success', + }, + ], +}; + +class _Gateway implements ApiGateway { + _Gateway(this.run); + + final JsonMap run; + final _events = StreamController.broadcast(); + + @override + Stream get frames => _events.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) => + switch (type) { + 'list_runs' => Future.value({ + 'runs': [run], + }), + 'get_run' => Future.value({'run_detail': run}), + _ => Future.error(UnsupportedError(type)), + }; + + void close() => _events.close(); +} + +Future _pump( + WidgetTester tester, + _Gateway gateway, { + required bool decide, +}) async { + tester.view.physicalSize = const Size(900, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final screen = RunsScreen( + gateway: gateway, + initialRunId: 9, + initialDecide: decide, + ); + await tester.pumpWidget(MaterialApp(home: Scaffold(body: screen))); + await tester.pumpAndSettle(); +} + +void main() { + for (final cupertino in [false, true]) { + testWidgets('a decide route opens the waiting prompt ($cupertino)', ( + tester, + ) async { + final gateway = _Gateway(_waitingRun()); + addTearDown(gateway.close); + tester.view.physicalSize = const Size(900, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final screen = RunsScreen( + gateway: gateway, + initialRunId: 9, + initialDecide: true, + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: screen)) + : MaterialApp(home: Scaffold(body: screen)), + ); + await tester.pumpAndSettle(); + + expect(find.byKey(decisionFeedbackKey), findsOneWidget); + expect( + find.text('Please review this recorded checkpoint.'), + findsOneWidget, + ); + + // Closing the prompt leaves the loaded detail underneath. + await tester.tap(find.text(decisionCancelLabel)); + await tester.pumpAndSettle(); + expect(find.byKey(decisionFeedbackKey), findsNothing); + expect(find.text('Human checkpoint'), findsOneWidget); + expect(find.byKey(decisionActionKey), findsOneWidget); + }); + } + + testWidgets('a decide route on a non-waiting run invents no prompt', ( + tester, + ) async { + final gateway = _Gateway(_finishedRun()); + addTearDown(gateway.close); + await _pump(tester, gateway, decide: true); + + expect(find.byKey(decisionFeedbackKey), findsNothing); + expect(find.byKey(decisionActionKey), findsNothing); + expect(find.text('Human checkpoint'), findsOneWidget); + }); + + testWidgets('a route without decide keeps the plain waiting detail', ( + tester, + ) async { + final gateway = _Gateway(_waitingRun()); + addTearDown(gateway.close); + await _pump(tester, gateway, decide: false); + + expect(find.byKey(decisionFeedbackKey), findsNothing); + expect(find.text('Human checkpoint'), findsOneWidget); + expect(find.byKey(decisionActionKey), findsOneWidget); + + // The landed button still opens the same prompt deliberately. + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); + expect(find.byKey(decisionFeedbackKey), findsOneWidget); + }); +}