import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../data/runs_repository.dart'; import '../domain/run_decisions.dart'; import '../domain/run_models.dart'; import 'action_refusal.dart'; import 'decision_dialog.dart'; import 'decision_wording.dart'; /// The run detail's deliberate human-decision entry point. /// /// Renders one native button only while [run] is genuinely waiting on a person. /// Nothing is sent until the operator opens the prompt, chooses an option and /// presses Confirm; cancel, selection and optional feedback stay local. A /// server refusal is shown verbatim in the prompt immediately, the draft is /// preserved and the run is re-read separately so [onRunChanged] still receives /// server truth without locking the prompt while that read is pending. class HumanDecisionAction extends StatefulWidget { const HumanDecisionAction({ super.key, required this.run, required this.gateway, required this.onRunChanged, this.cupertino, }); final JsonMap run; final ApiGateway gateway; final ValueChanged onRunChanged; /// Overrides the platform style; by default it follows the enclosing app. final bool? cupertino; @override State createState() => _HumanDecisionActionState(); } class _HumanDecisionActionState extends State { PendingDecision? _pending; bool _dialogOpen = false; @override void initState() { super.initState(); _pending = pendingDecision(widget.run); } @override void didUpdateWidget(covariant HumanDecisionAction oldWidget) { super.didUpdateWidget(oldWidget); _pending = pendingDecision(widget.run); } bool _usesCupertino(BuildContext context) { if (widget.cupertino != null) return widget.cupertino!; final material = Localizations.of( context, MaterialLocalizations, ); return material == null; } Future _open() async { final decision = _pending; if (decision == null || _dialogOpen) return; _dialogOpen = true; try { await showRunDecisionPrompt( context: context, run: widget.run, gateway: widget.gateway, cupertino: _usesCupertino(context), onRunChanged: _acceptRun, isCurrent: () => _owns(decision.runId), ); } finally { _dialogOpen = false; if (mounted) setState(() {}); } } void _acceptRun(JsonMap run) { if (!mounted) return; setState(() => _pending = pendingDecision(run)); widget.onRunChanged(run); } bool _owns(num id) => mounted && widget.run['id'] == id; @override Widget build(BuildContext context) { final decision = _pending; if (decision == null) return const SizedBox.shrink(); if (_usesCupertino(context)) { return CupertinoButton.filled( key: decisionActionKey, onPressed: _open, child: const Text(decisionActionLabel), ); } return FilledButton( key: decisionActionKey, onPressed: _open, child: const Text(decisionActionLabel), ); } } /// 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; }