feat(app): add deliberate run cancellation action

Port the browser's canCancel rule and cancel_run request into a native
Material/Cupertino confirmation. Opening the prompt or choosing Keep sends
nothing; a refusal stays visible with the server's words and the run is
re-read so the owner always receives server truth. Includes eligibility,
double-submit, disposal and narrow 2x-text tests plus R2b evidence.
This commit is contained in:
2026-10-21 14:41:33 +01:00
parent 3e6f950991
commit faa5866410
8 changed files with 865 additions and 0 deletions
@@ -0,0 +1,145 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'cancel_wording.dart';
/// Sends the confirmed cancellation. Returns null once the server has accepted
/// it, or the server's refusal verbatim; the prompt then stays open.
typedef CancelSubmit = Future<String?> Function();
/// Opens the native cancel confirmation for [runId].
///
/// Nothing is sent until the operator presses the confirm action, and the
/// dismiss action (`Keep`) only closes the prompt.
Future<void> showCancelRunPrompt({
required BuildContext context,
required num runId,
required bool cupertino,
required CancelSubmit onSubmit,
}) {
final prompt = _CancelPrompt(
runId: runId,
cupertino: cupertino,
onSubmit: onSubmit,
);
if (cupertino) {
return showCupertinoDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
class _CancelPrompt extends StatefulWidget {
const _CancelPrompt({
required this.runId,
required this.cupertino,
required this.onSubmit,
});
final num runId;
final bool cupertino;
final CancelSubmit onSubmit;
@override
State<_CancelPrompt> createState() => _CancelPromptState();
}
class _CancelPromptState extends State<_CancelPrompt> {
bool _sending = false;
String? _error;
void _keep() {
if (!_sending) Navigator.of(context).pop();
}
Future<void> _confirm() async {
if (_sending) return;
setState(() {
_sending = true;
_error = null;
});
final refusal = await widget.onSubmit();
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: Text(cancelDialogTitle(widget.runId)),
content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)),
actions: [
TextButton(
key: cancelKeepKey,
onPressed: _sending ? null : _keep,
child: const Text(cancelKeepLabel),
),
FilledButton(
key: cancelConfirmKey,
onPressed: _sending ? null : _confirm,
child: const Text(cancelConfirmLabel),
),
],
);
}
Widget _cupertino(BuildContext context) {
return CupertinoAlertDialog(
title: Text(cancelDialogTitle(widget.runId)),
content: _body(
errorStyle: TextStyle(
color: CupertinoColors.systemRed.resolveFrom(context),
),
),
actions: [
CupertinoDialogAction(
key: cancelKeepKey,
onPressed: _sending ? null : _keep,
child: const Text(cancelKeepLabel),
),
CupertinoDialogAction(
key: cancelConfirmKey,
isDestructiveAction: true,
onPressed: _sending ? null : _confirm,
child: const Text(cancelConfirmLabel),
),
],
);
}
Widget _body({required TextStyle errorStyle}) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(cancelDialogMessage),
if (_error case final error?)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(error, key: cancelErrorKey, style: errorStyle),
),
],
);
}
}
@@ -0,0 +1,31 @@
import '../../../core/api_gateway.dart';
/// Whether the operator may cancel [run], matching `canCancel` in
/// `web/src/actions.js` exactly:
///
/// `(executing || (status == "waiting" && export_pending_sequence > 0)) &&
/// !cancel_requested && !cleanup_unconfirmed`
///
/// The status word alone is not enough: a stale `running` status without
/// `executing` is not cancellable, while a run waiting on a pending session
/// export is.
bool canCancelRun(JsonMap? run) {
if (run == null) return false;
final exportPending = _number(run['export_pending_sequence']);
return (run['executing'] == true ||
(run['status'] == 'waiting' && exportPending > 0)) &&
run['cancel_requested'] != true &&
run['cleanup_unconfirmed'] != true;
}
/// The run id used by the cancel request, or null for a malformed run.
num? cancelRunId(JsonMap run) {
final id = run['id'];
return id is num ? id : null;
}
/// `Number(value) > 0`, tolerating numeric strings as the browser does.
double _number(dynamic value) {
if (value is num) return value.toDouble();
return double.tryParse('${value ?? ''}'.trim()) ?? 0;
}
@@ -0,0 +1,101 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../data/runs_repository.dart';
import 'cancel_dialog.dart';
import 'cancel_eligibility.dart';
import 'cancel_wording.dart';
/// The run detail's deliberate cancel entry point.
///
/// Renders one native button only while [run] is cancellable under the browser
/// client's rule. Opening the prompt or choosing [cancelKeepLabel] sends
/// nothing; only the confirm action asks the server to stop the run. A refusal
/// is shown verbatim in the kept-open prompt and the run is re-read, so
/// [onRunChanged] always receives server truth instead of a local guess.
class CancelRunAction extends StatefulWidget {
const CancelRunAction({
super.key,
required this.run,
required this.gateway,
required this.onRunChanged,
});
final JsonMap run;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
@override
State<CancelRunAction> createState() => _CancelRunActionState();
}
class _CancelRunActionState extends State<CancelRunAction> {
bool _dialogOpen = false;
bool _usesCupertino(BuildContext context) {
final material = Localizations.of<MaterialLocalizations>(
context,
MaterialLocalizations,
);
return material == null;
}
Future<void> _open() async {
final id = cancelRunId(widget.run);
if (id == null || !canCancelRun(widget.run) || _dialogOpen) return;
_dialogOpen = true;
try {
await showCancelRunPrompt(
context: context,
runId: id,
cupertino: _usesCupertino(context),
onSubmit: () => _submit(id),
);
} finally {
_dialogOpen = false;
if (mounted) setState(() {});
}
}
Future<String?> _submit(num id) async {
final repository = RunsRepository(widget.gateway);
try {
final run = await repository.cancelRun(id);
if (!mounted) return null;
widget.onRunChanged(run);
return null;
} catch (error) {
final refusal = describeCancelError(error);
if (!mounted) return refusal;
JsonMap? refreshed;
try {
refreshed = await repository.getRun(id);
} catch (_) {
// A failed re-read must not hide or replace the server's refusal.
}
if (!mounted) return refusal;
if (refreshed != null) widget.onRunChanged(refreshed);
return refusal;
}
}
@override
Widget build(BuildContext context) {
if (cancelRunId(widget.run) == null || !canCancelRun(widget.run)) {
return const SizedBox.shrink();
}
if (_usesCupertino(context)) {
return CupertinoButton.filled(
key: cancelActionKey,
onPressed: _open,
child: const Text(cancelActionLabel),
);
}
return FilledButton(
key: cancelActionKey,
onPressed: _open,
child: const Text(cancelActionLabel),
);
}
}
@@ -0,0 +1,23 @@
import 'package:flutter/widgets.dart';
/// The browser client's cancel wording, kept verbatim.
const cancelActionLabel = 'Cancel run';
const cancelDialogMessage = 'This asks the server to stop the active run.';
const cancelConfirmLabel = 'Cancel run';
const cancelKeepLabel = 'Keep';
/// Stable test/semantics keys shared by the action and its prompt.
const cancelActionKey = ValueKey<String>('cancel-run-action');
const cancelKeepKey = ValueKey<String>('cancel-run-keep');
const cancelConfirmKey = ValueKey<String>('cancel-run-confirm');
const cancelErrorKey = ValueKey<String>('cancel-run-error');
/// The cancel dialog's title: `Cancel run {id}?`.
String cancelDialogTitle(num runId) => 'Cancel run $runId?';
/// The server's refusal, verbatim. Only a blank error gets a generic sentence
/// so the prompt never claims a cancellation that did not happen.
String describeCancelError(Object error) {
final message = '$error'.trim();
return message.isEmpty ? 'The server did not cancel the run.' : message;
}
+96
View File
@@ -0,0 +1,96 @@
# R2b — native run cancellation
## What changed
New `lib/features/runs/actions/cancel*` slice plus its tests. No existing source
file was edited.
| File | Lines | Responsibility |
| --- | --- | --- |
| `lib/features/runs/actions/cancel_eligibility.dart` | 31 | Web-exact `canCancelRun`, run-id extraction, numeric export counter |
| `lib/features/runs/actions/cancel_wording.dart` | 23 | Web-verbatim words, dialog title, error text, test keys |
| `lib/features/runs/actions/cancel_dialog.dart` | 145 | Native Material/Cupertino confirmation and inline refusal |
| `lib/features/runs/actions/cancel_run_action.dart` | 101 | `CancelRunAction`, gating, send/refusal/resync orchestration |
| `test/features/runs/actions/cancel_test_support.dart` | 101 | Fake gateway, run fixtures, stateful host, app wrappers |
| `test/features/runs/actions/cancel_action_test.dart` | 192 | Eligibility and both-platform deliberate-confirm flows |
| `test/features/runs/actions/cancel_resilience_test.dart` | 176 | Refusal/resync, resync failure, double submit, disposal, 2x/narrow |
`CancelRunAction` takes the run, the shared `ApiGateway` and an
`onRunChanged` callback. It renders one native `FilledButton` (`Cancel run`) on
Material and one `CupertinoButton.filled` on Cupertino, and nothing at all when
the browser rule says the run is not cancellable. Platform style follows the
enclosing app (`MaterialLocalizations` presence); no extra style parameter or
dependency was added.
## Behaviour
Eligibility is a direct port of `canCancel` in `../web/src/actions.js`:
```
(executing || (status == "waiting" && export_pending_sequence > 0))
&& !cancel_requested && !cleanup_unconfirmed
```
A run with a stale `running` status but `executing == false` is therefore not
cancellable, while a `waiting` run with a pending session export is. A run
without a numeric `id` is not offered because the request cannot be addressed
(the pure eligibility function still matches the web rule exactly).
Opening the prompt sends nothing and `Keep` only closes it. The prompt uses the
web wording (`Cancel run {id}?`, `This asks the server to stop the active run.`,
`Cancel run`, `Keep`). Only the confirm action calls
`RunsRepository.cancelRun(id)`, which sends the exact envelope
`cancel_run {"run_id": id}`.
Both the dialog and the action guard the in-flight state: a second confirm tap
or a `Keep` tap while sending is ignored, and the dialog's actions are disabled
until the reply arrives. A successful reply closes the prompt and passes the
server's returned `run_detail` to `onRunChanged`; no local status is invented.
A refusal keeps the prompt open and shows the server's message verbatim. The
action then calls `RunsRepository.getRun(id)` and passes the refreshed run to
`onRunChanged`, so the owner sees server truth (for example the run finished
before cancellation). If the re-read also fails, the original refusal stays
visible and no synthetic run is delivered. Every asynchronous resume checks
`mounted` before `setState` or `onRunChanged`, so a late reply after disposal is
ignored.
## Checks actually run
```
flutter pub get # dependencies resolved
dart format lib/features/runs/actions/cancel*.dart \
test/features/runs/actions/cancel*.dart # clean
flutter analyze # No issues found!
flutter test test/features/runs/actions # 16 passed
flutter test # 45 passed
flutter build web # Built build/web (15.5s)
```
Focused coverage maps to the requested acceptance:
- eligibility: executing, export-wait, waiting without export, stale `running`
without `executing`, already stopping, cleanup unconfirmed, finished/failed;
plus widget visibility for the same states;
- both platforms: native prompt opens, nothing is sent on open or `Keep`, exact
`cancel_run` envelope, callback receives the returned run, action disappears;
- refusal: cancellation error shown verbatim, `get_run` resync delivered to the
owner, and a failed resync leaves the refusal visible with no callback;
- double submit: two confirm taps produce one `cancel_run`, both actions disable;
- stale disposal: a reply after the tree is replaced causes no exception and no
callback;
- 320x480 at 2x text: both prompts open with no rendering exception.
## Honest limits
- **Not wired into a run-detail screen.** This branch has no run-detail screen
or controller; the manager owns integration. There is therefore no real
browser interaction or capture for this widget. `flutter build web` proves
compilation only, not rendered behavior, and no visible feature is claimed.
- **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 with no
socket.
- No controller/screen/main/domain/repository/pubspec, `web/`, Go server,
installer or deployment file was changed. Nothing was committed, pushed or
deployed.
@@ -0,0 +1,192 @@
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/cancel_eligibility.dart';
import 'package:pipelines_app/features/runs/actions/cancel_wording.dart';
import 'cancel_test_support.dart';
void main() {
test('cancel eligibility matches the web canCancel exactly', () {
final cases = <(String, JsonMap, bool)>[
('executing run', executingRun(), true),
(
'waiting while a session export is pending',
executingRun(executing: false, status: 'waiting', exportPending: 2),
true,
),
(
'waiting with no pending export',
executingRun(executing: false, status: 'waiting'),
false,
),
(
'status says running but the run is not executing',
executingRun(executing: false),
false,
),
(
'cancellation already requested',
executingRun(cancelRequested: true),
false,
),
('cleanup unconfirmed', executingRun(cleanupUnconfirmed: true), false),
(
'completed run',
executingRun(executing: false, status: 'succeeded'),
false,
),
('failed run', executingRun(executing: false, status: 'failed'), false),
];
for (final (label, run, expected) in cases) {
expect(canCancelRun(run), expected, reason: label);
}
expect(canCancelRun(null), isFalse);
});
testWidgets(
'material cancel asks first, Keep sends nothing, then sends the envelope',
(tester) async {
final accepted = acceptedCancelRun();
final gateway = FakeCancelGateway(
(type, fields) async => {'run_detail': accepted},
);
final changed = <JsonMap>[];
await tester.pumpWidget(
cancelApp(
CancelHost(
gateway: gateway,
initial: executingRun(),
changed: changed,
),
cupertino: false,
),
);
expect(find.byKey(cancelActionKey), findsOneWidget);
expect(find.byType(FilledButton), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text(cancelDialogTitle(7)), findsOneWidget);
expect(find.text(cancelDialogMessage), findsOneWidget);
expect(find.text(cancelKeepLabel), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(cancelKeepKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(find.byKey(cancelActionKey), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(cancelConfirmKey));
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['cancel_run']);
expect(gateway.calls.single.fields, {'run_id': 7});
expect(changed.single, equals(accepted));
expect(find.byType(AlertDialog), findsNothing);
expect(find.byKey(cancelActionKey), findsNothing);
},
);
testWidgets(
'cupertino cancel uses a native prompt and sends only on confirm',
(tester) async {
final accepted = acceptedCancelRun();
final gateway = FakeCancelGateway(
(type, fields) async => {'run_detail': accepted},
);
final changed = <JsonMap>[];
await tester.pumpWidget(
cancelApp(
CancelHost(
gateway: gateway,
initial: executingRun(),
changed: changed,
),
cupertino: true,
),
);
expect(find.byKey(cancelActionKey), findsOneWidget);
expect(find.byType(CupertinoButton), findsOneWidget);
expect(find.byType(FilledButton), findsNothing);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
expect(find.text(cancelDialogTitle(7)), findsOneWidget);
expect(find.text(cancelDialogMessage), findsOneWidget);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(cancelKeepKey));
await tester.pumpAndSettle();
expect(gateway.calls, isEmpty);
expect(find.byType(CupertinoAlertDialog), findsNothing);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(cancelConfirmKey));
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['cancel_run']);
expect(gateway.calls.single.fields, {'run_id': 7});
expect(changed.single, equals(accepted));
expect(find.byType(CupertinoAlertDialog), findsNothing);
expect(find.byKey(cancelActionKey), findsNothing);
},
);
testWidgets('the action is absent for runs the web does not cancel', (
tester,
) async {
final gateway = FakeCancelGateway(
(type, fields) async => {'run_detail': executingRun()},
);
final changed = <JsonMap>[];
final cases = <(String, JsonMap, bool)>[
('executing', executingRun(), true),
(
'export wait',
executingRun(executing: false, status: 'waiting', exportPending: 1),
true,
),
(
'no export wait',
executingRun(executing: false, status: 'waiting'),
false,
),
('stale running status', executingRun(executing: false), false),
('already stopping', executingRun(cancelRequested: true), false),
('cleanup unconfirmed', executingRun(cleanupUnconfirmed: true), false),
('finished', executingRun(executing: false, status: 'succeeded'), false),
];
for (final (label, run, visible) in cases) {
await tester.pumpWidget(
cancelApp(
CancelHost(
key: ValueKey(label),
gateway: gateway,
initial: run,
changed: changed,
),
cupertino: false,
),
);
expect(
find.byKey(cancelActionKey),
visible ? findsOneWidget : findsNothing,
reason: label,
);
}
expect(gateway.calls, isEmpty);
expect(changed, isEmpty);
});
}
@@ -0,0 +1,176 @@
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/cancel_wording.dart';
import 'cancel_test_support.dart';
Future<void> _pump(
WidgetTester tester,
FakeCancelGateway gateway,
List<JsonMap> changed, {
bool cupertino = false,
double textScale = 1,
JsonMap? run,
}) async {
await tester.pumpWidget(
cancelApp(
CancelHost(
gateway: gateway,
initial: run ?? executingRun(),
changed: changed,
),
cupertino: cupertino,
textScale: textScale,
),
);
}
Future<void> _openAndConfirm(WidgetTester tester) async {
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(cancelConfirmKey));
}
void main() {
testWidgets('a refusal stays visible and delivers the resynced run', (
tester,
) async {
const refusal = 'run 7 already completed; nothing to cancel';
final refreshed = executingRun(executing: false, status: 'succeeded');
final gateway = FakeCancelGateway((type, fields) async {
if (type == 'cancel_run') throw const ProtocolError(refusal);
expect(type, 'get_run');
return {'run_detail': refreshed};
});
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _openAndConfirm(tester);
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']);
expect(gateway.calls.first.fields, {'run_id': 7});
expect(gateway.calls.last.fields, {'run_id': 7});
expect(find.text(refusal), findsOneWidget);
expect(find.byKey(cancelErrorKey), findsOneWidget);
expect(find.byType(AlertDialog), findsOneWidget);
expect(changed.single, equals(refreshed));
expect(find.byKey(cancelActionKey), findsNothing);
});
testWidgets('a failed resync never hides the refusal or invents a run', (
tester,
) async {
const refusal = 'server refused to stop the run';
final gateway = FakeCancelGateway((type, fields) async {
if (type == 'cancel_run') throw const ProtocolError(refusal);
throw const NotConnectedError();
});
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _openAndConfirm(tester);
await tester.pumpAndSettle();
expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']);
expect(find.text(refusal), findsOneWidget);
expect(find.byType(AlertDialog), findsOneWidget);
expect(changed, isEmpty);
expect(find.byKey(cancelActionKey), findsOneWidget);
});
testWidgets(
'confirm cannot submit twice while the cancellation is in flight',
(tester) async {
final reply = Completer<JsonMap>();
final gateway = FakeCancelGateway((type, fields) => reply.future);
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
final confirm = find.byKey(cancelConfirmKey);
await tester.tap(confirm);
await tester.tap(confirm);
await tester.pump();
expect(
gateway.calls.where((call) => call.type == 'cancel_run'),
hasLength(1),
);
expect(
tester.widget<FilledButton>(find.byKey(cancelConfirmKey)).onPressed,
isNull,
);
expect(
tester.widget<TextButton>(find.byKey(cancelKeepKey)).onPressed,
isNull,
);
expect(find.byType(AlertDialog), findsOneWidget);
reply.complete({'run_detail': acceptedCancelRun()});
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<JsonMap>();
final gateway = FakeCancelGateway((type, fields) => reply.future);
final changed = <JsonMap>[];
await _pump(tester, gateway, changed);
await _openAndConfirm(tester);
await tester.pump();
expect(gateway.calls, hasLength(1));
await tester.pumpWidget(const SizedBox());
reply.complete({'run_detail': acceptedCancelRun()});
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 = FakeCancelGateway(
(type, fields) async => {'run_detail': acceptedCancelRun()},
);
await _pump(
tester,
gateway,
<JsonMap>[],
cupertino: cupertino,
textScale: 2,
);
await tester.tap(find.byKey(cancelActionKey));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino');
expect(find.text(cancelDialogTitle(7)), findsOneWidget);
expect(find.text(cancelDialogMessage), findsOneWidget);
expect(
cupertino
? find.byType(CupertinoAlertDialog)
: find.byType(AlertDialog),
findsOneWidget,
);
expect(gateway.calls, isEmpty);
await tester.tap(find.byKey(cancelKeepKey));
await tester.pumpAndSettle();
}
});
}
@@ -0,0 +1,101 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/actions/cancel_run_action.dart';
typedef CancelHandler = Future<JsonMap> Function(String type, JsonMap fields);
/// A fake gateway that records every request and never owns a socket.
class FakeCancelGateway implements ApiGateway {
FakeCancelGateway(this.handler);
final CancelHandler handler;
final List<({String type, JsonMap fields})> calls = [];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
final copy = Map<String, dynamic>.from(fields);
calls.add((type: type, fields: copy));
return handler(type, copy);
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}
JsonMap executingRun({
num id = 7,
bool executing = true,
String status = 'running',
int exportPending = 0,
bool cancelRequested = false,
bool cleanupUnconfirmed = false,
}) => {
'id': id,
'title': 'Nightly build',
'status': status,
'executing': executing,
'export_pending_sequence': exportPending,
'cancel_requested': cancelRequested,
'cleanup_unconfirmed': cleanupUnconfirmed,
};
JsonMap acceptedCancelRun() =>
executingRun(executing: false, status: 'canceled', cancelRequested: true);
/// Owns the run like a run-detail screen would, so the callback's returned
/// server detail is what the action renders next.
class CancelHost extends StatefulWidget {
const CancelHost({
super.key,
required this.gateway,
required this.initial,
required this.changed,
});
final FakeCancelGateway gateway;
final JsonMap initial;
final List<JsonMap> changed;
@override
State<CancelHost> createState() => _CancelHostState();
}
class _CancelHostState extends State<CancelHost> {
late JsonMap _run = widget.initial;
@override
Widget build(BuildContext context) {
return CancelRunAction(
run: _run,
gateway: widget.gateway,
onRunChanged: (run) {
widget.changed.add(run);
setState(() => _run = run);
},
);
}
}
Widget cancelApp(
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)),
);
}