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.
This commit is contained in:
2026-10-22 11:52:22 +01:00
parent 81b2805cdd
commit 9344e6d3c0
5 changed files with 328 additions and 71 deletions
+1
View File
@@ -223,6 +223,7 @@ class _PipelinesAppState extends State<PipelinesApp> {
initialRunId: route.runId,
initialStageKey: route.stageKey,
initialVisit: route.visit,
initialDecide: route.decide,
listRefreshToken: _runsRefresh,
notifications: _notifications,
onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)),
@@ -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<int>? 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,
@@ -40,8 +40,6 @@ class HumanDecisionAction extends StatefulWidget {
class _HumanDecisionActionState extends State<HumanDecisionAction> {
PendingDecision? _pending;
bool _dialogOpen = false;
bool _sending = false;
Future<bool?>? _resync;
@override
void initState() {
@@ -69,11 +67,13 @@ class _HumanDecisionActionState extends State<HumanDecisionAction> {
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<HumanDecisionAction> {
}
}
Future<ActionRefusal?> _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<bool?> _resyncRun(PendingDecision decision) {
return _resync ??= _readRun(decision);
}
Future<bool?> _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<HumanDecisionAction> {
}
}
/// 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<void> showRunDecisionPrompt({
required BuildContext context,
required JsonMap run,
required ApiGateway gateway,
required ValueChanged<JsonMap> 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<JsonMap> onAccepted;
final bool Function() isCurrent;
bool _sending = false;
Future<bool?>? _resync;
Future<ActionRefusal?> 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<bool?> _resyncRun() => _resync ??= _readRun();
Future<bool?> _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;
+52
View File
@@ -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<RunsScreen> {
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<RunsScreen> {
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<RunsScreen> {
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<RunsScreen> {
@override
void dispose() {
controller.removeListener(_selectionChanged);
controller.removeListener(_detailChanged);
controller.dispose();
super.dispose();
}
@@ -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<JsonMap>.broadcast();
@override
Stream<JsonMap> get frames => _events.stream;
@override
Future<JsonMap> 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<void> _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);
});
}