diff --git a/app/lib/features/runs/actions/decision_action.dart b/app/lib/features/runs/actions/decision_action.dart new file mode 100644 index 00000000..5405accf --- /dev/null +++ b/app/lib/features/runs/actions/decision_action.dart @@ -0,0 +1,141 @@ +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 '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, the draft is preserved and +/// the run is re-read so [onRunChanged] always receives server truth. +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; + bool _sending = 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 showHumanDecisionPrompt( + context: context, + decision: decision, + cupertino: _usesCupertino(context), + onSubmit: (draft) => _submit(decision, draft), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(PendingDecision decision, DecisionDraft draft) async { + final option = draft.selected?.trim() ?? ''; + if (option.isEmpty || _sending) return null; + _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) { + final refusal = _describe(error); + if (!mounted) return refusal; + JsonMap? refreshed; + try { + refreshed = await repository.getRun(decision.runId); + } catch (_) { + // A failed re-read must not hide or replace the server's refusal. + } + if (refreshed != null && mounted) { + setState(() => _pending = pendingDecision(refreshed)); + widget.onRunChanged(refreshed); + } + return refusal; + } + if (!mounted) return null; + setState(() => _pending = pendingDecision(run)); + widget.onRunChanged(run); + return null; + } finally { + _sending = false; + } + } + + @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), + ); + } +} + +String _describe(Object error) { + final message = '$error'; + return message.trim().isEmpty ? 'The server refused the decision.' : message; +} diff --git a/app/lib/features/runs/actions/decision_dialog.dart b/app/lib/features/runs/actions/decision_dialog.dart new file mode 100644 index 00000000..9649ea16 --- /dev/null +++ b/app/lib/features/runs/actions/decision_dialog.dart @@ -0,0 +1,248 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/run_decisions.dart'; +import '../domain/run_models.dart'; +import 'decision_wording.dart'; + +/// Sends the draft to the server. Returns null on success, or the server's +/// refusal message verbatim; the prompt stays open with the draft intact. +typedef DecisionSubmit = Future Function(DecisionDraft draft); + +/// Opens the native decision prompt for [decision]. +Future showHumanDecisionPrompt({ + required BuildContext context, + required PendingDecision decision, + required bool cupertino, + required DecisionSubmit onSubmit, +}) { + final prompt = _DecisionPrompt( + decision: decision, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _DecisionPrompt extends StatefulWidget { + const _DecisionPrompt({ + required this.decision, + required this.cupertino, + required this.onSubmit, + }); + + final PendingDecision decision; + final bool cupertino; + final DecisionSubmit onSubmit; + + @override + State<_DecisionPrompt> createState() => _DecisionPromptState(); +} + +class _DecisionPromptState extends State<_DecisionPrompt> { + DecisionDraft _draft = const DecisionDraft(); + late final TextEditingController _feedback = TextEditingController(); + bool _sending = false; + String? _error; + + @override + void dispose() { + _feedback.dispose(); + super.dispose(); + } + + void _select(String option) { + if (_sending) return; + setState(() => _draft = _draft.select(option)); + } + + void _feedbackChanged(String value) => _draft = _draft.withFeedback(value); + + void _cancel() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _confirm() async { + if (_sending || !_draft.canSubmit) return; + setState(() { + _sending = true; + _error = null; + }); + final refusal = await widget.onSubmit(_draft); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + setState(() { + _sending = false; + _error = refusal; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: const Text(decisionWaitingTitle), + content: _body( + errorStyle: TextStyle(color: theme.colorScheme.error), + options: RadioGroup( + groupValue: _draft.selected, + onChanged: (value) { + if (value != null) _select(value); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final option in widget.decision.options) + RadioListTile( + value: option.key, + enabled: !_sending, + title: Text(option.key), + subtitle: _target(option), + ), + ], + ), + ), + feedback: TextField( + key: decisionFeedbackKey, + controller: _feedback, + enabled: !_sending, + decoration: const InputDecoration(labelText: decisionFeedbackLabel), + textInputAction: TextInputAction.done, + onChanged: _feedbackChanged, + onSubmitted: (_) => _confirm(), + ), + ), + actions: [ + TextButton( + onPressed: _sending ? null : _cancel, + child: const Text(decisionCancelLabel), + ), + FilledButton( + onPressed: _sending || !_draft.canSubmit ? null : _confirm, + child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: const Text(decisionWaitingTitle), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + options: RadioGroup( + groupValue: _draft.selected, + onChanged: (value) { + if (value != null) _select(value); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final option in widget.decision.options) + CupertinoButton( + onPressed: _sending ? null : () => _select(option.key), + child: Row( + children: [ + CupertinoRadio( + value: option.key, + useCheckmarkStyle: true, + enabled: !_sending, + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(option.key), + if (_targetText(option) case final target?) + Text(target), + ], + ), + ), + ], + ), + ), + ], + ), + ), + feedback: CupertinoTextField( + key: decisionFeedbackKey, + controller: _feedback, + enabled: !_sending, + placeholder: decisionFeedbackLabel, + textInputAction: TextInputAction.done, + onChanged: _feedbackChanged, + onSubmitted: (_) => _confirm(), + ), + ), + actions: [ + CupertinoDialogAction( + onPressed: _sending ? null : _cancel, + child: const Text(decisionCancelLabel), + ), + CupertinoDialogAction( + isDefaultAction: true, + onPressed: _sending || !_draft.canSubmit ? null : _confirm, + child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel), + ), + ], + ); + } + + Widget _body({ + required TextStyle errorStyle, + required Widget options, + required Widget feedback, + }) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(decisionMeta(widget.decision)), + if (widget.decision.instructions.trim().isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(widget.decision.instructions), + ), + Padding(padding: const EdgeInsets.only(top: 8), child: options), + Padding(padding: const EdgeInsets.only(top: 8), child: feedback), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: decisionErrorKey, style: errorStyle), + ), + ], + ); + } + + Widget? _target(DecisionOption option) { + final text = _targetText(option); + return text == null ? null : Text(text); + } + + String? _targetText(DecisionOption option) { + final text = decisionTargetText(option.target); + return text.isEmpty ? null : text; + } +} diff --git a/app/lib/features/runs/actions/decision_wording.dart b/app/lib/features/runs/actions/decision_wording.dart new file mode 100644 index 00000000..a9904946 --- /dev/null +++ b/app/lib/features/runs/actions/decision_wording.dart @@ -0,0 +1,24 @@ +import 'package:flutter/widgets.dart'; + +import '../domain/run_decisions.dart'; + +/// The browser client's decision wording, kept verbatim. +const decisionWaitingTitle = 'Waiting for your decision'; +const decisionActionLabel = 'Decide'; +const decisionFeedbackLabel = 'Feedback (optional)'; +const decisionCancelLabel = 'Cancel'; +const decisionConfirmLabel = 'Confirm decision'; +const decisionSendingLabel = 'Sending…'; + +/// Stable test/semantics keys shared by the action and its prompt. +const decisionActionKey = ValueKey('human-decision-action'); +const decisionFeedbackKey = ValueKey('human-decision-feedback'); +const decisionErrorKey = ValueKey('human-decision-error'); + +/// `{stage} · run {id} · {label}`, as the web decision card shows it. +String decisionMeta(PendingDecision decision) => + '${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}'; + +/// The option's target line, `→ {target}`, or "" when no target was declared. +String decisionTargetText(String target) => + target.trim().isEmpty ? '' : '→ $target'; diff --git a/app/notes/R2a.md b/app/notes/R2a.md new file mode 100644 index 00000000..30ec1ace --- /dev/null +++ b/app/notes/R2a.md @@ -0,0 +1,84 @@ +# R2a — native human-decision action + +## What changed + +New `lib/features/runs/actions/` slice (no existing source file edited): + +| File | Lines | Responsibility | +| --- | --- | --- | +| `decision_action.dart` | 141 | `HumanDecisionAction`, gating, submit/refusal/resync orchestration | +| `decision_dialog.dart` | 248 | Material `AlertDialog` / Cupertino `CupertinoAlertDialog` prompt | +| `decision_wording.dart` | 24 | Web-verbatim words, meta/target formatting and test keys | +| `test/.../decision_action_test.dart` | 237 | Material/Cupertino deliberate send and gating | +| `test/.../decision_resilience_test.dart` | 240 | refusal resync, double submit, disposal, 2x/narrow | + +`HumanDecisionAction` takes the run, the shared `ApiGateway` and an +`onRunChanged` callback. It renders one `FilledButton` (`Decide`) on Material +and one `CupertinoButton.filled` on Cupertino, and nothing at all when +`pendingDecision(run)` is null. Recorded waiting-step options therefore win over +the pinned graph, and a pending session export suppresses the action through the +existing domain rule without duplicating it here. + +Opening the prompt sends nothing. The prompt uses the web wording +(`Waiting for your decision`, `Feedback (optional)`, `Cancel`, +`Confirm decision`, `Sending…`), shows the stage/run meta line and each option's +`→ target` when declared. Confirm is disabled until an option is selected; +selecting itself only updates the draft. Confirm calls `RunsRepository.decideRun` +with the exact stage, trimmed option and trimmed optional feedback (blank +feedback is omitted by the repository). + +A refusal is shown verbatim inside the kept-open prompt; the option selection +and feedback controller are untouched. The action then calls +`RunsRepository.getRun` and passes the refreshed run to `onRunChanged`. A +successful decision passes the server's `run_detail` to `onRunChanged` and +closes the prompt. Both sends are guarded in the prompt and in the owner state; +buttons are disabled while `Sending…`. Every asynchronous resume checks +`mounted` before `setState` or `onRunChanged`, so a late reply after disposal is +ignored. + +Platform style follows the enclosing app: `MaterialApp` gets the Material +dialog and controls, `CupertinoApp` gets the Cupertino dialog with native +buttons/radios/field. No custom palette, font family, fixed button/row size, +dependency or CSS token was added; the theme's error color and default control +spacing are used. The one optional `cupertino` override exists for +callers/tests that do not wrap in either app. + +## Checks actually run + +``` +flutter pub get # dependencies resolved +dart format lib/features/runs/actions test/features/runs/actions +flutter analyze # No issues found! +flutter test test/features/runs # 18 passed +flutter test # 36 passed +flutter test test/features/runs/actions # 7 passed +flutter build web # Built build/web (14.2s) +``` + +Focused coverage maps to the requested acceptance: + +- material: action visible, dialog open, selection does not send, Confirm is + disabled before selection, exact `decide_run` stage/option/`looks good` + feedback, callback gets the decided run and the action disappears; +- cupertino: native `CupertinoAlertDialog`, disabled Confirm first, blank + feedback omitted, exact request fields; +- gating: running, export-pending and non-human runs render no action; +- refusal: `decide_run` then `get_run`, verbatim error still visible, selected + option and typed feedback retained, refreshed failed run delivered to owner; +- double submit: two Confirm taps produce one `decide_run`, Cancel is disabled + while sending; +- stale disposal: completing the decision after the tree is replaced produces + no exception and no owner callback; +- 320×480 at 2x text on both apps: prompt opens with no rendering exception. + +## Honest limits + +- **Not wired into a run-detail screen.** `lib/features/runs/` has no screen or + controller on this branch; the manager owns that integration. There is + therefore no real browser interaction or capture for this widget. The + `flutter build web` result proves compilation only, not rendered behavior. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + Source uses only portable Flutter/Cupertino/Material widgets. +- No real server or run was mutated. Tests use a local fake gateway. +- No repository/domain/controller/screen/main, `web/`, Go server, installer or + deployment file was changed. Nothing was committed, pushed or deployed. diff --git a/app/test/features/runs/actions/decision_action_test.dart b/app/test/features/runs/actions/decision_action_test.dart new file mode 100644 index 00000000..9d424b8f --- /dev/null +++ b/app/test/features/runs/actions/decision_action_test.dart @@ -0,0 +1,237 @@ +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_action.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; + +typedef _Handler = Future Function(String type, JsonMap fields); + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.handler); + + final _Handler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap _waitingRun({ + String status = 'waiting', + int exportPending = 0, + String type = 'human', + List options = const ['go', 'skip'], +}) => { + 'id': 7, + 'title': 'Report', + 'name': 'Build', + 'status': status, + 'current_stage': 'human', + 'export_pending_sequence': exportPending, + 'graph': { + 'stages': [ + { + 'key': 'human', + 'type': type, + 'prompt': 'Graph prompt', + 'edges': {'go': '#', 'skip': 'finish'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'status': 'waiting', + 'stage': 'human', + 'output': {'prompt': 'Ship it?', 'options': options}, + }, + ], +}; + +JsonMap _decided() => { + ..._waitingRun(), + 'status': 'succeeded', + 'steps': const [], +}; + +Widget _app(Widget child, {required bool cupertino, double textScale = 1}) { + if (cupertino) { + return CupertinoApp( + builder: (context, app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ), + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: (context, app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ), + home: Scaffold(body: Center(child: child)), + ); +} + +Future _pump( + WidgetTester tester, + _FakeGateway gateway, + JsonMap run, { + required bool cupertino, + required List changed, + double textScale = 1, +}) async { + await tester.pumpWidget( + _app( + HumanDecisionAction( + run: run, + gateway: gateway, + onRunChanged: changed.add, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _open(WidgetTester tester) async { + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets( + 'material decision waits for option and confirm, then sends exact fields', + (tester) async { + final gateway = _FakeGateway( + (type, fields) async => { + 'run_detail': type == 'decide_run' ? _decided() : _waitingRun(), + }, + ); + final changed = []; + await _pump( + tester, + gateway, + _waitingRun(), + cupertino: false, + changed: changed, + ); + + expect(find.byKey(decisionActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await _open(tester); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(decisionWaitingTitle), findsOneWidget); + expect(find.text('Ship it?'), findsOneWidget); + expect(find.text('→ SUCCESS'), findsOneWidget); + expect(gateway.calls, isEmpty); + + final confirm = find.widgetWithText(FilledButton, decisionConfirmLabel); + expect(tester.widget(confirm).onPressed, isNull); + + await tester.tap(find.text('go')); + await tester.pump(); + expect(gateway.calls, isEmpty); + expect(tester.widget(confirm).onPressed, isNotNull); + + await tester.enterText(find.byKey(decisionFeedbackKey), ' looks good '); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'stage': 'human', + 'option': 'go', + 'feedback': 'looks good', + }); + expect(changed.single['status'], 'succeeded'); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(decisionActionKey), findsNothing); + }, + ); + + testWidgets( + 'cupertino decision uses a native dialog and omits empty feedback', + (tester) async { + final gateway = _FakeGateway( + (type, fields) async => { + 'run_detail': type == 'decide_run' ? _decided() : _waitingRun(), + }, + ); + final changed = []; + await _pump( + tester, + gateway, + _waitingRun(), + cupertino: true, + changed: changed, + ); + + expect(find.byKey(decisionActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + await _open(tester); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.text(decisionWaitingTitle), findsOneWidget); + expect(gateway.calls, isEmpty); + + final confirm = find.widgetWithText( + CupertinoDialogAction, + decisionConfirmLabel, + ); + expect(tester.widget(confirm).onPressed, isNull); + await tester.tap(find.text('skip')); + await tester.pump(); + expect(gateway.calls, isEmpty); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'stage': 'human', + 'option': 'skip', + }); + expect(changed.single['status'], 'succeeded'); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }, + ); + + testWidgets('the action is absent unless a run is genuinely waiting', ( + tester, + ) async { + final gateway = _FakeGateway( + (type, fields) async => {'run_detail': _waitingRun()}, + ); + final changed = []; + for (final (label, run) in [ + ('not waiting', _waitingRun(status: 'running')), + ('export pending', _waitingRun(exportPending: 2)), + ('model stage', _waitingRun(type: 'model')), + ]) { + await _pump(tester, gateway, run, cupertino: false, changed: changed); + expect( + find.byKey(decisionActionKey), + findsNothing, + reason: '$label must not offer a decision', + ); + } + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/actions/decision_resilience_test.dart b/app/test/features/runs/actions/decision_resilience_test.dart new file mode 100644 index 00000000..d23981b5 --- /dev/null +++ b/app/test/features/runs/actions/decision_resilience_test.dart @@ -0,0 +1,240 @@ +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/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/decision_action.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; + +typedef _Handler = Future Function(String type, JsonMap fields); + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.handler); + + final _Handler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap _waitingRun() => { + 'id': 7, + 'title': 'Report', + 'status': 'waiting', + 'current_stage': 'human', + 'graph': { + 'stages': [ + { + 'key': 'human', + 'type': 'human', + 'prompt': 'Graph prompt', + 'edges': {'go': '#', 'skip': 'finish'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'status': 'waiting', + 'stage': 'human', + 'output': { + 'prompt': 'Ship it?', + 'options': ['go', 'skip'], + }, + }, + ], +}; + +JsonMap _decided() => { + ..._waitingRun(), + 'status': 'succeeded', + 'steps': const [], +}; + +Widget _app(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: Center(child: child)), + ); +} + +Future _pump( + WidgetTester tester, + _FakeGateway gateway, + List changed, { + bool cupertino = false, + double textScale = 1, +}) async { + await tester.pumpWidget( + _app( + HumanDecisionAction( + run: _waitingRun(), + gateway: gateway, + onRunChanged: changed.add, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _chooseGo(WidgetTester tester, {String feedback = ''}) async { + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.text('go')); + await tester.pump(); + if (feedback.isNotEmpty) { + await tester.enterText(find.byKey(decisionFeedbackKey), feedback); + } +} + +void main() { + testWidgets('a refusal stays visible and keeps the selected draft', ( + tester, + ) async { + const refusal = 'option "go" is not a valid outcome; choose one of: skip'; + final gateway = _FakeGateway((type, fields) async { + if (type == 'decide_run') throw const ProtocolError(refusal); + expect(type, 'get_run'); + return { + 'run_detail': { + ..._waitingRun(), + 'status': 'failed', + 'steps': const [], + }, + }; + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester, feedback: ' keep me '); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']); + expect(gateway.calls.last.fields, {'run_id': 7}); + expect(find.text(refusal), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect( + tester + .widget>(find.byType(RadioGroup)) + .groupValue, + 'go', + ); + expect( + tester + .widget(find.byKey(decisionFeedbackKey)) + .controller + ?.text, + ' keep me ', + ); + expect(changed.single['status'], 'failed'); + expect(find.byKey(decisionActionKey), findsNothing); + }); + + testWidgets('confirm cannot submit twice while the decision is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = _FakeGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester); + + final confirm = find.text(decisionConfirmLabel); + await tester.tap(confirm); + await tester.tap(confirm); + await tester.pump(); + + expect( + gateway.calls.where((call) => call.type == 'decide_run'), + hasLength(1), + ); + expect(find.text(decisionSendingLabel), findsOneWidget); + expect( + tester + .widget( + find.widgetWithText(TextButton, decisionCancelLabel), + ) + .onPressed, + isNull, + ); + + reply.complete({'run_detail': _decided()}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + }); + + testWidgets('a late reply after disposal is ignored safely', (tester) async { + final reply = Completer(); + final gateway = _FakeGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pump(); + expect(gateway.calls, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': _decided()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('both prompts fit 2x text at a narrow width', (tester) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + for (final cupertino in [false, true]) { + final gateway = _FakeGateway( + (type, fields) async => {'run_detail': _decided()}, + ); + await _pump( + tester, + gateway, + [], + cupertino: cupertino, + textScale: 2, + ); + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(decisionWaitingTitle), findsOneWidget); + expect(find.text('Ship it?'), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + } + }); +}